<?php
if ( ! defined( 'ABSPATH' ) ) exit;

class SVLD_Menu {

    public function __construct() {
        add_action( 'admin_menu', [ $this, 'add_admin_menu' ] );
        add_action( 'admin_enqueue_scripts', [ $this, 'enqueue_scripts' ] );
        add_action( 'admin_post_svld_save_settings', [ $this, 'handle_save_settings' ] );
    }

    public function add_admin_menu(): void {
        // Main menu page (Designer)
        $icon_svg = 'data:image/svg+xml;base64,' . base64_encode( '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 37"><path fill="#a7aaad" fill-rule="evenodd" transform="translate(0,-2)" d="M0.4,8.4l20-6c1.7,0,3,1.3,3,3v30c0,1.7-1.3,3-3,3l-20-6z M5.4,14.4h1.9v14H5.4z M9.9,14.4h1v14h-1z M12.9,14.4h1.9v14H12.9z M17.4,14.4h1v14h-1z"/></svg>' );
        add_menu_page(
            __( 'Label Designer', 'scanvault-label-designer' ),
            __( 'Label Designer', 'scanvault-label-designer' ),
            'manage_woocommerce',
            'svld-designer',
            [ $this, 'render_designer_page' ],
            $icon_svg,
            58
        );

        // Designer submenu (duplicate of main)
        add_submenu_page(
            'svld-designer',
            __( 'Label Designer', 'scanvault-label-designer' ),
            __( 'Designer', 'scanvault-label-designer' ),
            'manage_woocommerce',
            'svld-designer',
            [ $this, 'render_designer_page' ]
        );

        // Settings submenu
        add_submenu_page(
            'svld-designer',
            __( 'Label Settings', 'scanvault-label-designer' ),
            __( 'Settings', 'scanvault-label-designer' ),
            'manage_woocommerce',
            'svld-settings',
            [ $this, 'render_settings_page' ]
        );
    }

    public function enqueue_scripts( string $hook ): void {
        $allowed_hooks = [
            'toplevel_page_svld-designer',
            'label-designer_page_svld-settings',
        ];

        if ( ! in_array( $hook, $allowed_hooks, true ) ) {
            return;
        }

        // On settings page, also load metabox.js so the per-order print buttons work
        if ( $hook === 'label-designer_page_svld-settings' ) {
            wp_enqueue_script(
                'svld-metabox',
                SVLD_PLUGIN_URL . 'assets/js/metabox.js',
                [ 'jquery' ],
                SVLD_VERSION,
                true
            );
            wp_localize_script( 'svld-metabox', 'svld_metabox_params', [
                'ajax_url'           => admin_url( 'admin-ajax.php' ),
                'nonce'              => wp_create_nonce( 'svld_nonce' ),
                'generating'         => __( 'Generating PDF…', 'scanvault-label-designer' ),
                'open_pdf'           => __( 'Open PDF', 'scanvault-label-designer' ),
                'error'              => __( 'Failed to generate PDF. Please try again.', 'scanvault-label-designer' ),
                'print_action'       => 'svld_print_label',
                'order_print_action' => 'svld_print_order_labels',
            ] );
        }

        wp_enqueue_media();
        wp_enqueue_style( 'wp-color-picker' );
        wp_enqueue_script( 'wp-color-picker' );

        wp_enqueue_style(
            'svld-designer',
            SVLD_PLUGIN_URL . 'assets/css/designer.css',
            [],
            SVLD_VERSION
        );

        wp_enqueue_script(
            'svld-designer',
            SVLD_PLUGIN_URL . 'assets/js/designer.js',
            [ 'jquery', 'wp-color-picker' ],
            SVLD_VERSION,
            true
        );

        $layout   = get_option( 'svld_layout', svld_default_layout() );
        $settings = [
            'label_width'  => (int) get_option( 'svld_label_width', 100 ),
            'label_height' => (int) get_option( 'svld_label_height', 50 ),
            'bg_color'     => get_option( 'svld_bg_color', '#ffffff' ),
        ];

        wp_localize_script( 'svld-designer', 'svld_params', [
            'ajax_url'    => admin_url( 'admin-ajax.php' ),
            'nonce'       => wp_create_nonce( 'svld_nonce' ),
            'layout'      => $layout,
            'settings'    => $settings,
            'is_pro'      => true,
            'site_url'    => home_url(),
            'upgrade_url' => function_exists( 'svld_fs' ) ? svld_fs()->get_upgrade_url() : 'https://scan-vault.com/label-designer',
            'plugin_url'  => SVLD_PLUGIN_URL,
            'save_layout_action' => 'svld_save_layout',
            'print_label_action' => 'svld_print_label',
            'measurement_unit' => get_option( 'svld_measurement_unit', 'mm' ),
            'default_template' => get_option( 'svld_default_template', '' ),
            'pro_tooltip' => __( '🔒 Pro feature — Upgrade to unlock', 'scanvault-label-designer' ),
            'free_features' => [
                'can_move'          => true,
                'can_resize'        => true,
                'can_add'           => true,
                'can_delete'        => true,
                'can_save_template' => true,
            ],
        ] );
    }

    public function render_designer_page(): void {
        $width  = max( 50, (int) get_option( 'svld_label_width', 100 ) );
        $height = max( 25, (int) get_option( 'svld_label_height', 50 ) );

        // mm to px at 96dpi: 1mm ≈ 3.7795px
        $canvas_w = round( $width  * 3.7795 );
        $canvas_h = round( $height * 3.7795 );

        $templates = get_option( 'svld_templates', [] );
        $default_template = get_option( 'svld_default_template', '' );
        ?>
        <div class="wrap svld-designer-wrap">
            <h1><?php esc_html_e( 'Label Designer', 'scanvault-label-designer' ); ?></h1>
            <p class="svld-subtitle"><?php esc_html_e( 'Drag and position elements on your label canvas. Save multiple templates for different use cases.', 'scanvault-label-designer' ); ?></p>

            <!-- Compact Header: Size only (template and preset removed) -->
            <div class="svld-compact-header">
                <div class="svld-size-section">
                    <select id="svld-size-preset" title="<?php esc_html_e( 'Preset sizes', 'scanvault-label-designer' ); ?>">
                        <option value=""><?php esc_html_e( 'Size...', 'scanvault-label-designer' ); ?></option>
                        <option value="38x19" data-w="38" data-h="19" data-desc="<?php esc_attr_e( '(Small)', 'scanvault-label-designer' ); ?>">38×19 mm <?php esc_html_e( '(Small)', 'scanvault-label-designer' ); ?></option>
                        <option value="50x25" data-w="50" data-h="25" data-desc="<?php esc_attr_e( '(Medium)', 'scanvault-label-designer' ); ?>">50×25 mm <?php esc_html_e( '(Medium)', 'scanvault-label-designer' ); ?></option>
                        <option value="100x50" data-w="100" data-h="50" data-desc="<?php esc_attr_e( '(Standard)', 'scanvault-label-designer' ); ?>" selected>100×50 mm <?php esc_html_e( '(Standard)', 'scanvault-label-designer' ); ?></option>
                        <option value="100x100" data-w="100" data-h="100">100×100 mm</option>
                        <option value="210x297" data-w="210" data-h="297" data-desc="<?php esc_attr_e( '(A4)', 'scanvault-label-designer' ); ?>">210×297 mm <?php esc_html_e( '(A4)', 'scanvault-label-designer' ); ?></option>
                        <option value="216x279" data-w="216" data-h="279" data-desc="<?php esc_attr_e( '(Letter)', 'scanvault-label-designer' ); ?>">216×279 mm <?php esc_html_e( '(Letter)', 'scanvault-label-designer' ); ?></option>
                    </select>
                    <input type="number" id="svld-label-width" value="<?php echo esc_attr( $width ); ?>" min="10" max="500" title="<?php esc_html_e( 'Width', 'scanvault-label-designer' ); ?>">
                    <span class="svld-size-x">×</span>
                    <input type="number" id="svld-label-height" value="<?php echo esc_attr( $height ); ?>" min="10" max="500" title="<?php esc_html_e( 'Height', 'scanvault-label-designer' ); ?>">
                    <span class="svld-unit-label">mm</span>
                    <button type="button" id="svld-apply-size" class="button button-small"><?php esc_html_e( 'Apply', 'scanvault-label-designer' ); ?></button>
                </div>
            </div>

            <div class="svld-designer-grid">

                <!-- Elements Panel -->
                <div class="svld-panel svld-elements-panel">
                    <h2 class="svld-panel-title"><?php esc_html_e( 'Elements', 'scanvault-label-designer' ); ?></h2>
                    <p class="svld-panel-desc"><?php esc_html_e( 'Click + to add element, click element on canvas to edit.', 'scanvault-label-designer' ); ?></p>

                    <div class="svld-element-list">
                        <?php
                        $elements = [
                            'text'    => [ 'icon' => 'dashicons-edit', 'label' => __( 'Text', 'scanvault-label-designer' ) ],
                            'barcode' => [ 'icon' => 'dashicons-align-center', 'label' => __( 'Barcode', 'scanvault-label-designer' ) ],
                            'qr'      => [ 'icon' => 'dashicons-screenoptions', 'label' => __( 'QR Code', 'scanvault-label-designer' ) ],
                            'image'   => [ 'icon' => 'dashicons-format-image', 'label' => __( 'Image/Logo', 'scanvault-label-designer' ) ],
                        ];
                        foreach ( $elements as $type => $info ) : ?>
                        <div class="svld-element-item svld-draggable-element"
                             data-type="<?php echo esc_attr( $type ); ?>"
                             draggable="true"
                             title="<?php echo esc_attr( $info['label'] ); ?>">
                            <span class="svld-drag-handle" title="<?php esc_attr_e( 'Drag to canvas', 'scanvault-label-designer' ); ?>">
                                <span class="dashicons dashicons-menu"></span>
                            </span>
                            <button type="button" class="svld-add-element-btn" data-type="<?php echo esc_attr( $type ); ?>" title="<?php esc_attr_e( 'Click to add at center', 'scanvault-label-designer' ); ?>">
                                <span class="dashicons dashicons-plus-alt"></span>
                            </button>
                            <span class="dashicons <?php echo esc_attr( $info['icon'] ); ?>"></span>
                            <span class="svld-element-label"><?php echo esc_html( $info['label'] ); ?></span>
                        </div>
                        <?php endforeach; ?>
                    </div>

                    <!-- Layers Panel -->
                    <div class="svld-layers-section">
                        <h3 class="svld-layers-title">
                            <?php esc_html_e( 'Layers', 'scanvault-label-designer' ); ?>
                            <span class="svld-layers-hint"><?php esc_html_e( 'top', 'scanvault-label-designer' ); ?> <span aria-hidden="true" class="svld-layer-arrow">↓</span> <?php esc_html_e( 'bottom', 'scanvault-label-designer' ); ?></span>
                        </h3>
                        <div id="svld-layers-list" class="svld-layers-list">
                            <p class="svld-layers-empty"><?php esc_html_e( 'No elements yet.', 'scanvault-label-designer' ); ?></p>
                        </div>
                    </div>
                </div>

                <!-- Canvas Area -->
                <div class="svld-panel svld-canvas-panel">
                    <h2 class="svld-panel-title svld-preview-title">
                        <?php esc_html_e( 'Label Preview', 'scanvault-label-designer' ); ?>
                        <span class="svld-canvas-size"><span class="svld-canvas-size-value"><?php echo esc_html( $width . ' × ' . $height ); ?></span> <span class="svld-unit-label">mm</span></span>
                    </h2>

                    <!-- Zoom + Toolbar Controls -->
                    <!-- Quick Actions Toolbar -->
                    <div class="svld-quick-actions">
                        <span class="svld-quick-actions-label"><?php esc_html_e( 'History:', 'scanvault-label-designer' ); ?></span>
                        <button type="button" id="svld-undo" class="button button-small svld-action-btn" title="<?php esc_attr_e( 'Undo', 'scanvault-label-designer' ); ?>">
                            <span class="dashicons dashicons-undo"></span>
                        </button>
                        <button type="button" id="svld-redo" class="button button-small svld-action-btn" title="<?php esc_attr_e( 'Redo', 'scanvault-label-designer' ); ?>">
                            <span class="dashicons dashicons-redo"></span>
                        </button>
                        <span class="svld-action-separator"></span>
                        <span class="svld-quick-actions-label"><?php esc_html_e( 'Zoom:', 'scanvault-label-designer' ); ?></span>
                        <button type="button" id="svld-zoom-out" class="button button-small svld-action-btn" title="<?php esc_attr_e( 'Zoom Out', 'scanvault-label-designer' ); ?>">
                            <span class="dashicons dashicons-minus"></span>
                        </button>
                        <span id="svld-zoom-level" class="svld-zoom-level-inline">100%</span>
                        <button type="button" id="svld-zoom-in" class="button button-small svld-action-btn" title="<?php esc_attr_e( 'Zoom In', 'scanvault-label-designer' ); ?>">
                            <span class="dashicons dashicons-plus"></span>
                        </button>
                        <button type="button" id="svld-zoom-reset" class="button button-small svld-action-btn" title="<?php esc_attr_e( 'Reset Zoom', 'scanvault-label-designer' ); ?>">
                            <span class="dashicons dashicons-image-rotate"></span>
                        </button>
                        <span class="svld-action-separator"></span>
                        <button type="button" id="svld-toggle-grid" class="button button-small svld-action-btn" title="<?php esc_attr_e( 'Show Grid', 'scanvault-label-designer' ); ?>">
                            <span class="dashicons dashicons-grid-view"></span>
                        </button>
                        <button type="button" id="svld-toggle-snap" class="button button-small svld-action-btn" title="<?php esc_attr_e( 'Snap to Grid (0.5 mm)', 'scanvault-label-designer' ); ?>">
                            <span class="dashicons dashicons-admin-generic"></span>
                        </button>
                        <button type="button" id="svld-toggle-bounds" class="button button-small svld-action-btn" title="<?php esc_attr_e( 'Show Element Bounds', 'scanvault-label-designer' ); ?>">
                            <span class="dashicons dashicons-edit-page"></span>
                        </button>
                        <span class="svld-action-separator"></span>
                        <button type="button" id="svld-save-layout" class="button button-small svld-action-btn" title="<?php esc_attr_e( 'Quick save current layout', 'scanvault-label-designer' ); ?>">
                            <span class="dashicons dashicons-saved"></span>
                            <?php esc_html_e( 'Save', 'scanvault-label-designer' ); ?>
                        </button>
                        <button type="button" id="svld-reset-layout" class="button button-small svld-action-btn" title="<?php esc_attr_e( 'Clear canvas', 'scanvault-label-designer' ); ?>">
                            <span class="dashicons dashicons-trash"></span>
                            <?php esc_html_e( 'Clear', 'scanvault-label-designer' ); ?>
                        </button>
                    </div>

                    <!-- Context menu hint -->
                    <div class="svld-context-hint">
                        <span class="dashicons dashicons-info"></span>
                        <?php esc_html_e( 'Right-click an element to change layer order or duplicate it', 'scanvault-label-designer' ); ?>
                    </div>

                    <!-- Ruler + Canvas grid layout -->
                    <div class="svld-ruler-layout">

                        <!-- Top-left corner box -->
                        <div class="svld-ruler-corner"></div>

                        <!-- Horizontal ruler (outside scrollable area) -->
                        <div id="svld-ruler-h" class="svld-ruler svld-ruler-h">
                            <div class="svld-ruler-marks"></div>
                        </div>

                        <!-- Vertical ruler (outside scrollable area) -->
                        <div id="svld-ruler-v" class="svld-ruler svld-ruler-v">
                            <div class="svld-ruler-marks"></div>
                        </div>

                        <!-- Scrollable canvas wrapper (no rulers inside) -->
                        <div class="svld-canvas-wrapper">
                        <div id="svld-canvas-scale-host">
                            <div id="svld-canvas"
                                 class="svld-canvas"
                                 style="width:<?php echo esc_attr( $canvas_w ); ?>px; height:<?php echo esc_attr( $canvas_h ); ?>px;">

                                <!-- Grid overlay (hidden by default, toggled by JS) -->
                                <div id="svld-grid-overlay" class="svld-grid-overlay" style="display:none;"></div>

                                <!-- Alignment guides drawn here during drag -->
                                <div id="svld-guides-container" class="svld-guides-container"></div>

                                <!-- Elements rendered by JS -->
                                <div class="svld-canvas-placeholder">
                                    <span class="dashicons dashicons-tag"></span>
                                    <h3><?php esc_html_e( 'Your Label Canvas', 'scanvault-label-designer' ); ?></h3>
                                    <p><?php esc_html_e( 'Your canvas is currently empty. Start by adding elements:', 'scanvault-label-designer' ); ?></p>
                                    <p class="svld-placeholder-actions">
                                        <strong><?php esc_html_e( '+ Text, + Barcode, + QR Code', 'scanvault-label-designer' ); ?></strong>
                                        <?php esc_html_e( ' buttons above', 'scanvault-label-designer' ); ?>
                                    </p>
                                    <p class="svld-placeholder-preset">
                                        <?php esc_html_e( 'Or select a', 'scanvault-label-designer' ); ?>
                                        <strong><?php esc_html_e( 'Label Preset', 'scanvault-label-designer' ); ?></strong>
                                        <?php esc_html_e( 'to start from a template', 'scanvault-label-designer' ); ?>
                                    </p>
                                </div>
                            </div>
                        </div>

                        <!-- Rubber-band selection (inside wrapper, outside canvas so not affected by transform) -->
                        <div id="svld-rubber-band" class="svld-rubber-band" style="display:none;"></div>
                    </div><!-- /.svld-canvas-wrapper -->

                    </div><!-- /.svld-ruler-layout -->

                    <!-- Drag/resize position tooltip (fixed to viewport) -->
                    <div id="svld-drag-tooltip" class="svld-drag-tooltip" style="display:none;"></div>

                    <div class="svld-canvas-actions">
                        <button id="svld-test-print" class="button">
                            <span class="dashicons dashicons-printer"></span>
                            <?php esc_html_e( 'Test Print (Sample)', 'scanvault-label-designer' ); ?>
                        </button>
                        <span class="svld-save-status" id="svld-save-status"></span>
                    </div>
                </div>

                <!-- Properties Panel -->
                <div class="svld-panel svld-properties-panel">
                    <h2 class="svld-panel-title"><?php esc_html_e( 'Properties', 'scanvault-label-designer' ); ?></h2>

                    <div id="svld-no-selection" class="svld-no-selection">
                        <div class="svld-empty-icon">
                            <span class="dashicons dashicons-admin-generic"></span>
                        </div>
                        <h3><?php esc_html_e( 'No Element Selected', 'scanvault-label-designer' ); ?></h3>
                        <p><?php esc_html_e( 'Select an element on the canvas to edit its properties.', 'scanvault-label-designer' ); ?></p>

                        <div class="svld-quick-tips">
                            <h4><?php esc_html_e( '⚡ Quick Tips', 'scanvault-label-designer' ); ?></h4>
                            <ul>
                                <li><?php esc_html_e( 'Drag elements from the sidebar to the canvas', 'scanvault-label-designer' ); ?></li>
                                <li><?php esc_html_e( 'Right-click element for layer options', 'scanvault-label-designer' ); ?></li>
                                <li><?php esc_html_e( 'Shift+Click to multi-select elements', 'scanvault-label-designer' ); ?></li>
                            </ul>
                        </div>

                        <div class="svld-keyboard-shortcuts">
                            <h4><?php esc_html_e( '⌨️ Keyboard Shortcuts', 'scanvault-label-designer' ); ?></h4>
                            <div class="svld-shortcut-list">
                                <div class="svld-shortcut">
                                    <span class="svld-shortcut-key">Delete/Backspace</span>
                                    <span><?php esc_html_e( 'Remove element', 'scanvault-label-designer' ); ?></span>
                                </div>
                                <div class="svld-shortcut">
                                    <span class="svld-shortcut-key">Arrow keys</span>
                                    <span><?php esc_html_e( 'Nudge (1mm)', 'scanvault-label-designer' ); ?></span>
                                </div>
                                <div class="svld-shortcut">
                                    <span class="svld-shortcut-key">Shift + Arrows</span>
                                    <span><?php esc_html_e( 'Nudge (0.1mm)', 'scanvault-label-designer' ); ?></span>
                                </div>
                                <div class="svld-shortcut">
                                    <span class="svld-shortcut-key">Ctrl+Z</span>
                                    <span><?php esc_html_e( 'Undo', 'scanvault-label-designer' ); ?></span>
                                </div>
                                <div class="svld-shortcut">
                                    <span class="svld-shortcut-key">Ctrl+Y</span>
                                    <span><?php esc_html_e( 'Redo', 'scanvault-label-designer' ); ?></span>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div id="svld-properties-form" class="svld-properties-form" style="display:none;">
                        <div class="svld-prop-group">
                            <label><?php esc_html_e( 'Visible', 'scanvault-label-designer' ); ?></label>
                            <label class="svld-toggle">
                                <input type="checkbox" id="svld-prop-visible" checked>
                                <span class="svld-toggle-slider"></span>
                            </label>
                        </div>

                        <div class="svld-prop-group svld-text-props">
                            <label><?php esc_html_e( 'Font Size (pt)', 'scanvault-label-designer' ); ?></label>
                            <input type="number" id="svld-prop-font-size" min="6" max="48" value="10" class="small-text">
                        </div>

                        <div class="svld-prop-group" id="svld-prop-fit-width-group">
                            <label><?php esc_html_e( 'Fit to Width', 'scanvault-label-designer' ); ?></label>
                            <label class="svld-toggle">
                                <input type="checkbox" id="svld-prop-fit-width">
                                <span class="svld-toggle-slider"></span>
                            </label>
                            <small class="description"><?php esc_html_e( 'Auto-scale content to fit element size', 'scanvault-label-designer' ); ?></small>
                        </div>

                        <div class="svld-prop-group" id="svld-prop-multi-line-group" style="display:none;">
                            <label><?php esc_html_e( 'Multi-line', 'scanvault-label-designer' ); ?></label>
                            <label class="svld-toggle">
                                <input type="checkbox" id="svld-prop-multi-line">
                                <span class="svld-toggle-slider"></span>
                            </label>
                            <small class="description"><?php esc_html_e( 'Use full height for text wrapping', 'scanvault-label-designer' ); ?></small>
                        </div>

                        <div class="svld-prop-group svld-text-props">
                            <label><?php esc_html_e( 'Text Style', 'scanvault-label-designer' ); ?></label>
                            <div class="svld-text-style-buttons">
                                <button type="button" id="svld-prop-bold" class="svld-style-btn" title="<?php esc_attr_e( 'Bold', 'scanvault-label-designer' ); ?>">
                                    <span class="dashicons dashicons-editor-bold"></span>
                                </button>
                                <button type="button" id="svld-prop-italic" class="svld-style-btn" title="<?php esc_attr_e( 'Italic', 'scanvault-label-designer' ); ?>">
                                    <span class="dashicons dashicons-editor-italic"></span>
                                </button>
                                <button type="button" id="svld-prop-underline" class="svld-style-btn" title="<?php esc_attr_e( 'Underline', 'scanvault-label-designer' ); ?>">
                                    <span class="dashicons dashicons-editor-underline"></span>
                                </button>
                            </div>
                        </div>

                        <div class="svld-prop-group svld-text-props">
                            <label><?php esc_html_e( 'Alignment', 'scanvault-label-designer' ); ?></label>
                            <div class="svld-align-buttons">
                                <button type="button" id="svld-prop-align-left" class="svld-style-btn" data-align="left" title="<?php esc_attr_e( 'Align Left', 'scanvault-label-designer' ); ?>">
                                    <span class="dashicons dashicons-editor-alignleft"></span>
                                </button>
                                <button type="button" id="svld-prop-align-center" class="svld-style-btn" data-align="center" title="<?php esc_attr_e( 'Align Center', 'scanvault-label-designer' ); ?>">
                                    <span class="dashicons dashicons-editor-aligncenter"></span>
                                </button>
                                <button type="button" id="svld-prop-align-right" class="svld-style-btn" data-align="right" title="<?php esc_attr_e( 'Align Right', 'scanvault-label-designer' ); ?>">
                                    <span class="dashicons dashicons-editor-alignright"></span>
                                </button>
                            </div>
                        </div>

                        <hr class="svld-prop-divider">

                        <div class="svld-prop-group svld-datasource-props" style="display:none;">
                            <label><?php esc_html_e( 'Data Source', 'scanvault-label-designer' ); ?></label>
							<select id="svld-prop-datasource">
								<optgroup label="<?php esc_html_e( "Product Data", "scanvault-label-designer" ); ?>">
									<option value="product_name"><?php esc_html_e( "Product Name", "scanvault-label-designer" ); ?></option>
									<option value="product_sku"><?php esc_html_e( "Product SKU", "scanvault-label-designer" ); ?></option>
									<option value="product_price"><?php esc_html_e( "Product Price", "scanvault-label-designer" ); ?></option>
									<option value="product_id"><?php esc_html_e( "Product ID", "scanvault-label-designer" ); ?></option>
									<option value="product_link"><?php esc_html_e( "Product Link", "scanvault-label-designer" ); ?></option>
								</optgroup>
									<optgroup label="<?php esc_html_e( "Product Attributes", "scanvault-label-designer" ); ?>">
										<option value="product_stock"><?php esc_html_e( "Stock Quantity", "scanvault-label-designer" ); ?></option>
										<option value="product_weight"><?php esc_html_e( "Weight", "scanvault-label-designer" ); ?></option>
										<option value="product_length"><?php esc_html_e( "Length", "scanvault-label-designer" ); ?></option>
										<option value="product_width"><?php esc_html_e( "Width", "scanvault-label-designer" ); ?></option>
										<option value="product_height"><?php esc_html_e( "Height", "scanvault-label-designer"); ?></option>
										<option value="product_dimensions"><?php esc_html_e( "Dimensions (LxWxH)", "scanvault-label-designer" ); ?></option>
										<option value="product_categories"><?php esc_html_e( "Product Categories", "scanvault-label-designer" ); ?></option>
										<option value="product_tags"><?php esc_html_e( "Product Tags", "scanvault-label-designer" ); ?></option>
										<option value="product_short_description"><?php esc_html_e( "Short Description", "scanvault-label-designer" ); ?></option>
										<option value="product_total_sales"><?php esc_html_e( "Total Sales", "scanvault-label-designer" ); ?></option>
									</optgroup>
									<optgroup label="<?php esc_html_e( "Order Data", "scanvault-label-designer" ); ?>">
										<option value="order_number"><?php esc_html_e( "Order Number", "scanvault-label-designer" ); ?></option>
										<option value="order_date"><?php esc_html_e( "Order Date", "scanvault-label-designer" ); ?></option>
										<option value="order_total"><?php esc_html_e( "Order Total (incl. tax)", "scanvault-label-designer" ); ?></option>
										<option value="order_subtotal"><?php esc_html_e( "Subtotal (excl. tax)", "scanvault-label-designer" ); ?></option>
										<option value="order_tax"><?php esc_html_e( "Tax Amount", "scanvault-label-designer" ); ?></option>
										<option value="order_shipping_cost"><?php esc_html_e( "Shipping Cost", "scanvault-label-designer" ); ?></option>
										<option value="order_discount"><?php esc_html_e( "Discount", "scanvault-label-designer" ); ?></option>
										<option value="order_status"><?php esc_html_e( "Order Status", "scanvault-label-designer" ); ?></option>
										<option value="order_item_count"><?php esc_html_e( "Item Count", "scanvault-label-designer" ); ?></option>
										<option value="order_items_list"><?php esc_html_e( "Items List (names only)", "scanvault-label-designer" ); ?></option>
										<option value="order_invoice_full"><?php esc_html_e( "Invoice (Items + Totals)", "scanvault-label-designer" ); ?></option>
									</optgroup>
									<optgroup label="<?php esc_html_e( "Customer Data", "scanvault-label-designer" ); ?>">
										<option value="customer_first_name"><?php esc_html_e( "First Name", "scanvault-label-designer" ); ?></option>
										<option value="customer_last_name"><?php esc_html_e( "Last Name", "scanvault-label-designer" ); ?></option>
										<option value="customer_full_name"><?php esc_html_e( "Full Name", "scanvault-label-designer" ); ?></option>
										<option value="customer_email"><?php esc_html_e( "Email", "scanvault-label-designer" ); ?></option>
										<option value="customer_phone"><?php esc_html_e( "Phone", "scanvault-label-designer" ); ?></option>
										<option value="customer_company"><?php esc_html_e( "Company", "scanvault-label-designer" ); ?></option>
									</optgroup>
									<optgroup label="<?php esc_html_e( "Billing Address", "scanvault-label-designer" ); ?>">
										<option value="billing_address"><?php esc_html_e( "Full Address", "scanvault-label-designer" ); ?></option>
										<option value="billing_address_1"><?php esc_html_e( "Address Line 1", "scanvault-label-designer" ); ?></option>
										<option value="billing_address_2"><?php esc_html_e( "Address Line 2", "scanvault-label-designer" ); ?></option>
										<option value="billing_city"><?php esc_html_e( "City", "scanvault-label-designer" ); ?></option>
										<option value="billing_state"><?php esc_html_e( "State / Region", "scanvault-label-designer" ); ?></option>
										<option value="billing_postcode"><?php esc_html_e( "Postcode", "scanvault-label-designer" ); ?></option>
										<option value="billing_country"><?php esc_html_e( "Country", "scanvault-label-designer" ); ?></option>
									</optgroup>
									<optgroup label="<?php esc_html_e( "Shipping Address", "scanvault-label-designer" ); ?>">
										<option value="shipping_address"><?php esc_html_e( "Full Address", "scanvault-label-designer" ); ?></option>
										<option value="shipping_address_1"><?php esc_html_e( "Address Line 1", "scanvault-label-designer" ); ?></option>
										<option value="shipping_address_2"><?php esc_html_e( "Address Line 2", "scanvault-label-designer" ); ?></option>
										<option value="shipping_city"><?php esc_html_e( "City", "scanvault-label-designer" ); ?></option>
										<option value="shipping_state"><?php esc_html_e( "State / Region", "scanvault-label-designer" ); ?></option>
										<option value="shipping_postcode"><?php esc_html_e( "Postcode", "scanvault-label-designer" ); ?></option>
										<option value="shipping_country"><?php esc_html_e( "Country", "scanvault-label-designer" ); ?></option>
									</optgroup>
									<optgroup label="<?php esc_html_e( "Shipping & Payment", "scanvault-label-designer" ); ?>">
										<option value="shipping_method"><?php esc_html_e( "Shipping Method", "scanvault-label-designer" ); ?></option>
										<option value="payment_method"><?php esc_html_e( "Payment Method", "scanvault-label-designer" ); ?></option>
									</optgroup>
									<optgroup label="<?php esc_html_e( "Shop / Store Info", "scanvault-label-designer" ); ?>">
										<option value="shop_name"><?php esc_html_e( "Shop Name", "scanvault-label-designer" ); ?></option>
										<option value="shop_email"><?php esc_html_e( "Shop Email", "scanvault-label-designer" ); ?></option>
										<option value="shop_phone"><?php esc_html_e( "Shop Phone", "scanvault-label-designer" ); ?></option>
										<option value="shop_address"><?php esc_html_e( "Shop Address", "scanvault-label-designer" ); ?></option>
										<option value="shop_city"><?php esc_html_e( "Shop City", "scanvault-label-designer" ); ?></option>
										<option value="shop_country"><?php esc_html_e( "Shop Country", "scanvault-label-designer" ); ?></option>
										<option value="shop_postcode"><?php esc_html_e( "Shop Postcode", "scanvault-label-designer" ); ?></option>
									</optgroup>
								<optgroup label="<?php esc_html_e( "Other", "scanvault-label-designer" ); ?>">
									<option value="site_url"><?php esc_html_e( "Website URL", "scanvault-label-designer" ); ?></option>
									<option value="current_date"><?php esc_html_e( "Current Date", "scanvault-label-designer" ); ?></option>
									<option value="custom"><?php esc_html_e( "Custom Text/Value", "scanvault-label-designer" ); ?></option>
								</optgroup>
							</select>
                        </div>

                        <div class="svld-prop-group svld-customtext-props" style="display:none;">
                            <label><?php esc_html_e( 'Custom Text', 'scanvault-label-designer' ); ?></label>
                            <input type="text" id="svld-prop-customtext" class="regular-text" placeholder="<?php esc_attr_e( 'Enter custom text...', 'scanvault-label-designer' ); ?>">
                        </div>



                        <!-- Text direction toggle (shown only for invoice element) -->
                        <div class="svld-prop-group svld-invoice-direction-props" style="display:none;">
                            <label><?php esc_html_e( 'Text Direction', 'scanvault-label-designer' ); ?></label>
                            <div class="svld-text-style-buttons">
                                <button type="button" id="svld-prop-dir-ltr" class="svld-style-btn svld-dir-btn active" data-dir="ltr" title="<?php esc_attr_e( 'Left to Right (English, French…)', 'scanvault-label-designer' ); ?>">
                                    LTR
                                </button>
                                <button type="button" id="svld-prop-dir-rtl" class="svld-style-btn svld-dir-btn" data-dir="rtl" title="<?php esc_attr_e( 'Right to Left (Arabic, Hebrew…)', 'scanvault-label-designer' ); ?>">
                                    RTL
                                </button>
                            </div>
                        </div>

                        <div class="svld-prop-group svld-invoice-props" style="display:none;">
                            <label><?php esc_html_e( 'Invoice Options', 'scanvault-label-designer' ); ?></label>

                            <!-- Items Table Columns -->
                            <div style="margin-top:10px;padding:8px;background:#f9f9f9;border-radius:4px;">
                                <div style="font-size:11px;font-weight:600;color:#444;margin-bottom:6px;">
                                    <?php esc_html_e( 'Items Table', 'scanvault-label-designer' ); ?>
                                </div>
                                <div style="display:grid;grid-template-columns:1fr 1fr;gap:4px 12px;">
                                    <label style="display:flex;align-items:center;gap:6px;font-size:11px;">
                                        <input type="checkbox" id="svld-prop-show-item-image">
                                        <?php esc_html_e( 'Product Image', 'scanvault-label-designer' ); ?>
                                    </label>
                                    <label style="display:flex;align-items:center;gap:6px;font-size:11px;">
                                        <input type="checkbox" id="svld-prop-show-item-qty" checked>
                                        <?php esc_html_e( 'Quantity', 'scanvault-label-designer' ); ?>
                                    </label>
                                    <label style="display:flex;align-items:center;gap:6px;font-size:11px;">
                                        <input type="checkbox" id="svld-prop-show-item-price" checked>
                                        <?php esc_html_e( 'Price', 'scanvault-label-designer' ); ?>
                                    </label>
                                </div>
                            </div>
                            
                            <!-- Totals Section -->
                            <div style="margin-top:10px;padding:8px;background:#f9f9f9;border-radius:4px;">
                                <div style="font-size:11px;font-weight:600;color:#444;margin-bottom:6px;">
                                    <?php esc_html_e( 'Totals', 'scanvault-label-designer' ); ?>
                                </div>
                                <div style="display:grid;grid-template-columns:1fr 1fr;gap:4px 12px;">
                                    <label style="display:flex;align-items:center;gap:6px;font-size:11px;">
                                        <input type="checkbox" id="svld-prop-show-subtotal" checked>
                                        <?php esc_html_e( 'Subtotal', 'scanvault-label-designer' ); ?>
                                    </label>
                                    <label style="display:flex;align-items:center;gap:6px;font-size:11px;">
                                        <input type="checkbox" id="svld-prop-show-tax" checked>
                                        <?php esc_html_e( 'Tax', 'scanvault-label-designer' ); ?>
                                    </label>
                                    <label style="display:flex;align-items:center;gap:6px;font-size:11px;">
                                        <input type="checkbox" id="svld-prop-show-shipping" checked>
                                        <?php esc_html_e( 'Shipping', 'scanvault-label-designer' ); ?>
                                    </label>
                                    <label style="display:flex;align-items:center;gap:6px;font-size:11px;">
                                        <input type="checkbox" id="svld-prop-show-discount">
                                        <?php esc_html_e( 'Discount', 'scanvault-label-designer' ); ?>
                                    </label>
                                    <label style="display:flex;align-items:center;gap:6px;font-size:11px;grid-column:1/-1;">
                                        <input type="checkbox" id="svld-prop-show-total" checked>
                                        <strong><?php esc_html_e( 'TOTAL', 'scanvault-label-designer' ); ?></strong>
                                    </label>
                                </div>
                            </div>
                            
                            <!-- Payment & Shipping Info -->
                            <div style="margin-top:10px;padding:8px;background:#f9f9f9;border-radius:4px;">
                                <div style="font-size:11px;font-weight:600;color:#444;margin-bottom:6px;">
                                    <?php esc_html_e( 'Additional Info', 'scanvault-label-designer' ); ?>
                                </div>
                                <div style="display:grid;grid-template-columns:1fr 1fr;gap:4px 12px;">
                                    <label style="display:flex;align-items:center;gap:6px;font-size:11px;">
                                        <input type="checkbox" id="svld-prop-show-payment">
                                        <?php esc_html_e( 'Payment Method', 'scanvault-label-designer' ); ?>
                                    </label>
                                    <label style="display:flex;align-items:center;gap:6px;font-size:11px;">
                                        <input type="checkbox" id="svld-prop-show-shipping-via">
                                        <?php esc_html_e( 'Shipping Via', 'scanvault-label-designer' ); ?>
                                    </label>
                                </div>
                            </div>
                        </div>

                        <div class="svld-prop-group svld-image-props" style="display:none;">
                            <label><?php esc_html_e( 'Image Source', 'scanvault-label-designer' ); ?></label>
                            <select id="svld-prop-image-datasource">
                                <option value="custom"><?php esc_html_e( 'Custom URL', 'scanvault-label-designer' ); ?></option>
                                <option value="product_image"><?php esc_html_e( 'Product Image', 'scanvault-label-designer' ); ?></option>
                            </select>
                        </div>

                        <div class="svld-prop-group svld-image-props svld-image-url-props" style="display:none;">
                            <label><?php esc_html_e( 'Image URL', 'scanvault-label-designer' ); ?></label>
                            <input type="text" id="svld-prop-imageurl" class="regular-text" placeholder="<?php esc_attr_e( 'https://example.com/image.png', 'scanvault-label-designer' ); ?>">
                            <button type="button" id="svld-prop-select-image" class="button" style="margin-top:5px;padding:4px 8px;" title="<?php esc_html_e( 'Select from Media Library', 'scanvault-label-designer' ); ?>">
                                <span class="dashicons dashicons-upload"></span>
                            </button>
                        </div>

                        <div class="svld-prop-group svld-image-props svld-product-image-props" style="display:none;">
                            <label><?php esc_html_e( 'Product Image', 'scanvault-label-designer' ); ?></label>
                            <small class="description"><?php esc_html_e( 'Use the main product image from your catalog', 'scanvault-label-designer' ); ?></small>
                        </div>
                        <hr class="svld-prop-divider">

                        <div class="svld-prop-group">
                            <label><?php esc_html_e( 'X Position', 'scanvault-label-designer' ); ?> (<span class="svld-unit-label">mm</span>)</label>
                            <input type="number" id="svld-prop-x" min="0" step="0.5" class="small-text">
                        </div>

                        <div class="svld-prop-group">
                            <label><?php esc_html_e( 'Y Position', 'scanvault-label-designer' ); ?> (<span class="svld-unit-label">mm</span>)</label>
                            <input type="number" id="svld-prop-y" min="0" step="0.5" class="small-text">
                        </div>

                        <div class="svld-prop-group">
                            <label><?php esc_html_e( 'Width', 'scanvault-label-designer' ); ?> (<span class="svld-unit-label">mm</span>)</label>
                            <input type="number" id="svld-prop-width" min="5" step="0.5" class="small-text">
                        </div>

                        <div class="svld-prop-group">
                            <label><?php esc_html_e( 'Height', 'scanvault-label-designer' ); ?> (<span class="svld-unit-label">mm</span>)</label>
                            <input type="number" id="svld-prop-height" min="3" step="0.5" class="small-text">
                        </div>

                        <div class="svld-prop-group">
                            <label><?php esc_html_e( 'Keep Proportional', 'scanvault-label-designer' ); ?></label>
                            <label class="svld-toggle">
                                <input type="checkbox" id="svld-prop-proportional">
                                <span class="svld-toggle-slider"></span>
                            </label>
                            <small class="description"><?php esc_html_e( 'Maintain aspect ratio when resizing', 'scanvault-label-designer' ); ?></small>
                        </div>

                        <div class="svld-prop-group svld-barcode-props">
                            <label><?php esc_html_e( 'Barcode Type', 'scanvault-label-designer' ); ?></label>
                            <select id="svld-prop-barcode-type">
                                <option value="C128"><?php esc_html_e( 'Code 128 (Recommended)', 'scanvault-label-designer' ); ?></option>
                                <option value="C39"><?php esc_html_e( 'Code 39', 'scanvault-label-designer' ); ?></option>
                                <option value="EAN13"><?php esc_html_e( 'EAN-13', 'scanvault-label-designer' ); ?></option>
                                <option value="EAN8"><?php esc_html_e( 'EAN-8', 'scanvault-label-designer' ); ?></option>
                                <option value="UPCA"><?php esc_html_e( 'UPC-A', 'scanvault-label-designer' ); ?></option>
                                <option value="UPCE"><?php esc_html_e( 'UPC-E', 'scanvault-label-designer' ); ?></option>
                                <option value="I25"><?php esc_html_e( 'Interleaved 2 of 5', 'scanvault-label-designer' ); ?></option>
                                <option value="POSTNET"><?php esc_html_e( 'POSTNET', 'scanvault-label-designer' ); ?></option>
                            </select>
                            <small class="svld-validation-hint" id="svld-barcode-validation-hint"></small>
                        </div>

                        <div class="svld-prop-group svld-qr-props">
                            <label><?php esc_html_e( 'QR Code Type', 'scanvault-label-designer' ); ?></label>
                            <select id="svld-prop-qr-type">
                                <option value="QRCODE,H"><?php esc_html_e( 'QR Code (Standard)', 'scanvault-label-designer' ); ?></option>
                                <option value="DATAMATRIX"><?php esc_html_e( 'DataMatrix', 'scanvault-label-designer' ); ?></option>
                                <option value="PDF417"><?php esc_html_e( 'PDF417', 'scanvault-label-designer' ); ?></option>
                            </select>
                            <small class="svld-validation-hint" id="svld-qr-validation-hint"></small>
                        </div>

                        <div class="svld-prop-group svld-barcode-props">
                            <label><?php esc_html_e( 'Show barcode text', 'scanvault-label-designer' ); ?></label>
                            <input type="checkbox" id="svld-prop-show-text">
                        </div>

                        <!-- Data Source Preview Panel -->
                        <div class="svld-data-source-preview" id="svld-data-source-preview" style="display:none;">
                            <label><?php esc_html_e( '📊 Data Preview', 'scanvault-label-designer' ); ?></label>
                            <div class="svld-preview-box" id="svld-preview-content">
                                <p class="svld-preview-placeholder"><?php esc_html_e( 'Select an element to preview its data', 'scanvault-label-designer' ); ?></p>
                            </div>
                        </div>
                        <hr class="svld-prop-divider">

                        <div class="svld-prop-actions">
                            <button id="svld-prop-duplicate" class="button"><?php esc_html_e( 'Duplicate', 'scanvault-label-designer' ); ?></button>
                            <button id="svld-prop-remove" class="button svld-btn-danger"><?php esc_html_e( 'Remove', 'scanvault-label-designer' ); ?></button>
                        </div>
                    </div>
                </div>

            </div><!-- .svld-designer-grid -->
        </div>
        <?php
    }

    public function render_settings_page(): void {
        // Get saved templates
        $templates = get_option( 'svld_templates', [] );
        $default_template = get_option( 'svld_default_template', '' );

        // Get selected templates for each position
        $product_template    = get_option( 'svld_product_page_template', $default_template );
        $order_template      = get_option( 'svld_order_metabox_template', $default_template );
        $order_bulk_template = get_option( 'svld_order_bulk_action_template', '' );
        $bulk_template       = get_option( 'svld_bulk_action_template', $default_template );
        $invoice_template    = get_option( 'svld_invoice_tab_template', '' );
        $scanner_template    = get_option( 'svld_scanner_modal_template', $default_template );
        ?>
        <div class="wrap svld-settings-wrap">
            <h1><?php esc_html_e( 'Label Settings', 'scanvault-label-designer' ); ?></h1>

            <?php if ( isset( $_GET['saved'] ) ) : ?>
            <div class="notice notice-success is-dismissible"><p><?php esc_html_e( 'Settings saved.', 'scanvault-label-designer' ); ?></p></div>
            <?php endif; ?>

            <?php if ( ! empty( $templates ) ) : ?>
            <div class="notice notice-info">
                <p>
                    <strong><?php esc_html_e( 'Tip:', 'scanvault-label-designer' ); ?></strong>
                    <?php esc_html_e( 'When you set a template as "Default" in the Manage Templates modal, it will be automatically selected for all print positions below.', 'scanvault-label-designer' ); ?>
                </p>
            </div>
            <?php endif; ?>

            <?php
            // Helper: render a template <select> dropdown
            $render_template_select = function( string $name, string $id, string $selected_val, string $empty_label ) use ( $templates, $default_template ) {
                echo '<select name="' . esc_attr( $name ) . '" id="' . esc_attr( $id ) . '" class="regular-text">';
                echo '<option value="">' . esc_html( $empty_label ) . '</option>';
                foreach ( $templates as $tpl_id => $tpl ) {
                    $label = $tpl['name'];
                    if ( $tpl_id === $default_template ) {
                        $label .= ' (' . __( 'Default', 'scanvault-label-designer' ) . ')';
                    }
                    echo '<option value="' . esc_attr( $tpl_id ) . '" ' . selected( $selected_val, $tpl_id, false ) . '>' . esc_html( $label ) . '</option>';
                }
                echo '</select>';
            };
            ?>
            <form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
                <?php wp_nonce_field( 'svld_save_settings', 'svld_settings_nonce' ); ?>
                <input type="hidden" name="action" value="svld_save_settings">

                <!-- ── Group: Products ─────────────────────────────────────── -->
                <h2 class="title"><?php esc_html_e( 'Product Printing', 'scanvault-label-designer' ); ?></h2>
                <table class="form-table">
                    <tbody>
                        <tr>
                            <th scope="row"><?php esc_html_e( 'Product Edit Page', 'scanvault-label-designer' ); ?></th>
                            <td>
                                <?php $render_template_select( 'svld_product_page_template', 'svld_product_page_template', $product_template, __( '— Select —', 'scanvault-label-designer' ) ); ?>
                                <p class="description"><?php esc_html_e( 'Template used when printing a label from the product edit page metabox.', 'scanvault-label-designer' ); ?></p>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><?php esc_html_e( 'Bulk Actions (Products List)', 'scanvault-label-designer' ); ?></th>
                            <td>
                                <?php $render_template_select( 'svld_bulk_action_template', 'svld_bulk_action_template', $bulk_template, __( '— Select —', 'scanvault-label-designer' ) ); ?>
                                <p class="description"><?php esc_html_e( 'Template used when bulk printing labels from WooCommerce → Products list.', 'scanvault-label-designer' ); ?></p>
                            </td>
                        </tr>
                    </tbody>
                </table>

                <!-- ── Group: Orders ───────────────────────────────────────── -->
                <h2 class="title"><?php esc_html_e( 'Order Printing', 'scanvault-label-designer' ); ?></h2>
                <table class="form-table">
                    <tbody>
                        <tr>
                            <th scope="row"><?php esc_html_e( 'Order Metabox', 'scanvault-label-designer' ); ?></th>
                            <td>
                                <?php $render_template_select( 'svld_order_metabox_template', 'svld_order_metabox_template', $order_template, __( '— Select —', 'scanvault-label-designer' ) ); ?>
                                <p class="description"><?php esc_html_e( 'Template used when printing a label from the WooCommerce order edit page metabox.', 'scanvault-label-designer' ); ?></p>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><?php esc_html_e( 'Bulk Actions (Orders List)', 'scanvault-label-designer' ); ?></th>
                            <td>
                                <?php $render_template_select( 'svld_order_bulk_action_template', 'svld_order_bulk_action_template', $order_bulk_template, __( '— Same as Order Metabox —', 'scanvault-label-designer' ) ); ?>
                                <p class="description"><?php esc_html_e( 'Template used for the "Print Order Labels" bulk action on WooCommerce → Orders list. Leave blank to use the Order Metabox template.', 'scanvault-label-designer' ); ?></p>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><?php esc_html_e( 'Invoice Tab', 'scanvault-label-designer' ); ?></th>
                            <td>
                                <?php $render_template_select( 'svld_invoice_tab_template', 'svld_invoice_tab_template', $invoice_template, __( '— None —', 'scanvault-label-designer' ) ); ?>
                                <p class="description"><?php esc_html_e( 'Template available in the Invoice tab on the order page for invoice printing.', 'scanvault-label-designer' ); ?></p>
                            </td>
                        </tr>
                    </tbody>
                </table>

                <!-- ── Group: Scanner ──────────────────────────────────────── -->
                <h2 class="title"><?php esc_html_e( 'Scanner Integration', 'scanvault-label-designer' ); ?></h2>
                <table class="form-table">
                    <tbody>
                        <tr>
                            <th scope="row"><?php esc_html_e( 'Scanner Modal', 'scanvault-label-designer' ); ?></th>
                            <td>
                                <?php $render_template_select( 'svld_scanner_modal_template', 'svld_scanner_modal_template', $scanner_template, __( '— Use Default —', 'scanvault-label-designer' ) ); ?>
                                <p class="description"><?php esc_html_e( 'Template used when Business subscribers click "Print Label" in the ScanVault scanner modal.', 'scanvault-label-designer' ); ?></p>
                            </td>
                        </tr>
                    </tbody>
                </table>

                <!-- ── Group: PDF Settings ─────────────────────────────────── -->
                <h2 class="title"><?php esc_html_e( 'PDF Settings', 'scanvault-label-designer' ); ?></h2>
                <table class="form-table">
                    <tbody>
                        <tr>
                            <th scope="row"><?php esc_html_e( 'PDF Label Font', 'scanvault-label-designer' ); ?></th>
                            <td>
                                <?php
                                $saved_font   = get_option( 'svld_label_font', svld_get_default_font() );
                                $auto_default = svld_get_default_font();
                                $font_labels  = [
                                    'dejavusans' => __( 'DejaVu Sans — Universal Unicode (Arabic, Cyrillic, Greek, Latin…)', 'scanvault-label-designer' ),
                                    'dejavuserif'=> __( 'DejaVu Serif — Serif Unicode', 'scanvault-label-designer' ),
                                    'dejavusansmono' => __( 'DejaVu Sans Mono — Monospace Unicode', 'scanvault-label-designer' ),
                                    'freesans'   => __( 'FreeSans — Extended Unicode (includes more scripts)', 'scanvault-label-designer' ),
                                    'helvetica'  => __( 'Helvetica — Latin only (smallest file)', 'scanvault-label-designer' ),
                                    'times'      => __( 'Times — Latin serif only', 'scanvault-label-designer' ),
                                    'courier'    => __( 'Courier — Latin monospace only', 'scanvault-label-designer' ),
                                    'cid0cs'     => __( 'CID-0cs — Simplified Chinese (中文简体)', 'scanvault-label-designer' ),
                                    'cid0ct'     => __( 'CID-0ct — Traditional Chinese (中文繁體)', 'scanvault-label-designer' ),
                                    'cid0jp'     => __( 'CID-0jp — Japanese (日本語)', 'scanvault-label-designer' ),
                                    'cid0kr'     => __( 'CID-0kr — Korean (한국어)', 'scanvault-label-designer' ),
                                ];
                                $groups = [
                                    __( 'Universal Unicode', 'scanvault-label-designer' ) => [ 'dejavusans', 'dejavuserif', 'dejavusansmono', 'freesans' ],
                                    __( 'Latin Only', 'scanvault-label-designer' )         => [ 'helvetica', 'times', 'courier' ],
                                    __( 'East Asian (CJK)', 'scanvault-label-designer' )   => [ 'cid0cs', 'cid0ct', 'cid0jp', 'cid0kr' ],
                                ];
                                ?>
                                <select name="svld_label_font" id="svld_label_font" class="regular-text">
                                    <?php foreach ( $groups as $group_label => $fonts ) : ?>
                                    <optgroup label="<?php echo esc_attr( $group_label ); ?>">
                                        <?php foreach ( $fonts as $font_key ) : ?>
                                        <option value="<?php echo esc_attr( $font_key ); ?>"
                                            <?php selected( $saved_font, $font_key ); ?>>
                                            <?php echo esc_html( $font_labels[ $font_key ] ); ?>
                                            <?php if ( $font_key === $auto_default ) : ?> — <?php esc_html_e( 'auto-detected', 'scanvault-label-designer' ); ?><?php endif; ?>
                                        </option>
                                        <?php endforeach; ?>
                                    </optgroup>
                                    <?php endforeach; ?>
                                </select>
                                <p class="description">
                                    <?php
                                    printf(
                                        /* translators: %s: font name */
                                        esc_html__( 'Font used in all PDF labels. Auto-detected default for your locale: %s.', 'scanvault-label-designer' ),
                                        '<strong>' . esc_html( $font_labels[ $auto_default ] ?? $auto_default ) . '</strong>'
                                    );
                                    ?>
                                    <?php esc_html_e( 'Choose a CJK font if your site is in Chinese, Japanese, or Korean. For Russian, Arabic, Hindi and other non-Latin scripts use DejaVu Sans.', 'scanvault-label-designer' ); ?>
                                </p>
                            </td>
                        </tr>

                        <tr>
                            <th scope="row"><?php esc_html_e( 'Measurement Units', 'scanvault-label-designer' ); ?></th>
                            <td>
                                <label for="svld_measurement_unit"><?php esc_html_e( 'Select unit for label dimensions:', 'scanvault-label-designer' ); ?></label>
                                <select name="svld_measurement_unit" id="svld_measurement_unit" class="regular-text">
                                    <option value="mm" <?php selected( get_option( 'svld_measurement_unit', 'mm' ), 'mm' ); ?>>
                                        <?php esc_html_e( 'Millimeters (mm) — Default', 'scanvault-label-designer' ); ?>
                                    </option>
                                    <option value="cm" <?php selected( get_option( 'svld_measurement_unit', 'mm' ), 'cm' ); ?>>
                                        <?php esc_html_e( 'Centimeters (cm)', 'scanvault-label-designer' ); ?>
                                    </option>
                                    <option value="in" <?php selected( get_option( 'svld_measurement_unit', 'mm' ), 'in' ); ?>>
                                        <?php esc_html_e( 'Inches (in)', 'scanvault-label-designer' ); ?>
                                    </option>
                                    <option value="pt" <?php selected( get_option( 'svld_measurement_unit', 'mm' ), 'pt' ); ?>>
                                        <?php esc_html_e( 'Points (pt)', 'scanvault-label-designer' ); ?>
                                    </option>
                                </select>
                                <p class="description">
                                    <?php esc_html_e( 'Choose the unit system for label width and height. Millimeters is the default and recommended for most label printers. This will be used for all label dimensions.', 'scanvault-label-designer' ); ?>
                                </p>
                            </td>
                        </tr>

                    </tbody>
                </table>

                <?php submit_button( __( 'Save Settings', 'scanvault-label-designer' ) ); ?>
            </form>

            <?php if ( empty( $templates ) ) : ?>
            <div class="notice notice-warning">
                <p><?php esc_html_e( 'No templates created yet. Go to the Label Designer page to create and save templates first.', 'scanvault-label-designer' ); ?></p>
            </div>
            <?php endif; ?>

        </div>
        <?php
    }

    public function handle_save_settings(): void {
        check_admin_referer( 'svld_save_settings', 'svld_settings_nonce' );

        if ( ! current_user_can( 'manage_woocommerce' ) ) {
            wp_die( esc_html__( 'Unauthorized', 'scanvault-label-designer' ) );
        }

        // Save template selections for each position
        $templates = get_option( 'svld_templates', [] );

        // Product page template
        $product_template = sanitize_text_field( wp_unslash( $_POST['svld_product_page_template'] ?? '' ) );
        if ( $product_template && isset( $templates[ $product_template ] ) ) {
            update_option( 'svld_product_page_template', $product_template );
        } else {
            update_option( 'svld_product_page_template', '' );
        }

        // Order metabox template
        $order_template = sanitize_text_field( wp_unslash( $_POST['svld_order_metabox_template'] ?? '' ) );
        if ( $order_template && isset( $templates[ $order_template ] ) ) {
            update_option( 'svld_order_metabox_template', $order_template );
        } else {
            update_option( 'svld_order_metabox_template', '' );
        }

        // Bulk action template (Products list)
        $bulk_template = sanitize_text_field( wp_unslash( $_POST['svld_bulk_action_template'] ?? '' ) );
        if ( $bulk_template && isset( $templates[ $bulk_template ] ) ) {
            update_option( 'svld_bulk_action_template', $bulk_template );
        } else {
            update_option( 'svld_bulk_action_template', '' );
        }

        // Order bulk action template (Orders list)
        $order_bulk_template = sanitize_text_field( wp_unslash( $_POST['svld_order_bulk_action_template'] ?? '' ) );
        if ( $order_bulk_template && isset( $templates[ $order_bulk_template ] ) ) {
            update_option( 'svld_order_bulk_action_template', $order_bulk_template );
        } else {
            update_option( 'svld_order_bulk_action_template', '' );
        }

        // Invoice tab template
        $invoice_template = sanitize_text_field( wp_unslash( $_POST['svld_invoice_tab_template'] ?? '' ) );
        if ( $invoice_template && isset( $templates[ $invoice_template ] ) ) {
            update_option( 'svld_invoice_tab_template', $invoice_template );
        } else {
            update_option( 'svld_invoice_tab_template', '' );
        }

        // Scanner modal template
        $scanner_template = sanitize_text_field( wp_unslash( $_POST['svld_scanner_modal_template'] ?? '' ) );
        if ( $scanner_template && isset( $templates[ $scanner_template ] ) ) {
            update_option( 'svld_scanner_modal_template', $scanner_template );
        } else {
            update_option( 'svld_scanner_modal_template', '' );
        }

        // Label font
        $allowed_fonts = [ 'dejavusans', 'dejavuserif', 'dejavusansmono', 'freesans', 'helvetica', 'times', 'courier', 'cid0cs', 'cid0ct', 'cid0jp', 'cid0kr' ];
        $label_font = sanitize_text_field( wp_unslash( $_POST['svld_label_font'] ?? '' ) );
        if ( in_array( $label_font, $allowed_fonts, true ) ) {
            update_option( 'svld_label_font', $label_font );
        } else {
            delete_option( 'svld_label_font' ); // fall back to auto-detected default
        }

        // Measurement unit
        $allowed_units = [ 'mm', 'cm', 'in', 'pt' ];
        $measurement_unit = sanitize_text_field( wp_unslash( $_POST['svld_measurement_unit'] ?? 'mm' ) );
        if ( in_array( $measurement_unit, $allowed_units, true ) ) {
            update_option( 'svld_measurement_unit', $measurement_unit );
        } else {
            update_option( 'svld_measurement_unit', 'mm' ); // fall back to default
        }

        wp_safe_redirect( admin_url( 'admin.php?page=svld-settings&saved=1' ) );
        exit;
    }
}
