<?php

if (!defined('ABSPATH')) { exit; }
?>
<div class="aieo-dmm-section">
    <h2><?php esc_html_e('Product discounts', 'ai-eshop-optimizer'); ?></h2>
    <p class="description">
        <?php esc_html_e('Set a % discount that applies to products matching a brand, a category, a need, or any combination. Pick one or more brands (one discount row per brand) and/or categories and/or needs, and choose whether the dimensions combine with AND or OR. Leave a dimension empty to match "any" (under AND) or to ignore that dimension (under OR). Duplicates (same brand + categories + needs + operator + percent + dates + notes) are detected and skipped.', 'ai-eshop-optimizer'); ?>
    </p>

    <form id="aieo-dmm-brand-discount-form" class="aieo-dmm-form">
        <input type="hidden" name="id" value="0">

        <!-- ============================================================
             Shared eligibility section — IDENTICAL layout/order across
             gifts, discounts, and free-shipping rules. The fields here
             match the same grid in those other forms.
             ============================================================ -->
        <div class="aieo-dmm-grid">
            <p>
                <label><?php esc_html_e('Label (internal)', 'ai-eshop-optimizer'); ?></label>
                <input type="text" name="label" class="regular-text" placeholder="<?php esc_attr_e('e.g. Q4 promo, Black Friday', 'ai-eshop-optimizer'); ?>">
            </p>
            <p>
                <label><?php esc_html_e('Brand(s)', 'ai-eshop-optimizer'); ?></label>
                <select name="brand_term_ids[]" multiple class="aieo-dmm-brand-select regular-text"></select>
                <span class="description"><?php esc_html_e('Leave empty to apply to any brand.', 'ai-eshop-optimizer'); ?></span>
            </p>
            <p>
                <label><?php esc_html_e('Category/ies', 'ai-eshop-optimizer'); ?></label>
                <select name="category_term_ids[]" multiple class="aieo-dmm-category-select regular-text"></select>
                <span class="description"><?php esc_html_e('Leave empty to apply to any category.', 'ai-eshop-optimizer'); ?></span>
            </p>
            <p>
                <label><?php esc_html_e('Need(s)', 'ai-eshop-optimizer'); ?></label>
                <select name="need_term_ids[]" multiple class="aieo-dmm-need-select regular-text"></select>
                <span class="description"><?php esc_html_e('Leave empty to apply to any need (or skip if you don\'t use the Need taxonomy).', 'ai-eshop-optimizer'); ?></span>
            </p>
            <p>
                <label><?php esc_html_e('Minimum qualifying subtotal', 'ai-eshop-optimizer'); ?></label>
                <input type="number" name="min_subtotal" step="0.01" min="0" value="0">
                <span class="description"><?php esc_html_e('0 = no minimum; the discount applies to every targeted product regardless of cart size.', 'ai-eshop-optimizer'); ?></span>
            </p>
            <p>
                <label><?php esc_html_e('Threshold scope', 'ai-eshop-optimizer'); ?></label>
                <select name="min_subtotal_scope">
                    <option value="cart_total"><?php esc_html_e('Whole cart total', 'ai-eshop-optimizer'); ?></option>
                    <option value="targeted"><?php esc_html_e('Subtotal of matching items only', 'ai-eshop-optimizer'); ?></option>
                </select>
                <span class="description"><?php esc_html_e('"Whole cart total" = sum of every line. "Subtotal of matching items" = only lines hit by the filters above.', 'ai-eshop-optimizer'); ?></span>
            </p>
        </div>
        <div style="margin-top:14px;">
            <?php echo AIEO_DMM_Product_Picker::render_field(array(
                'name'     => 'product_ids',
                'mode'     => 'include',
                'label'    => __('Specific products (optional)', 'ai-eshop-optimizer'),
                'help'     => __('Pick simple products, whole variable products, or specific variations. When set, the discount applies ONLY when the cart contains at least one of these (in addition to the brand / category / need filters above). Variations roll up to their parent.', 'ai-eshop-optimizer'),
                'selected' => isset($edit_product_ids) ? $edit_product_ids : array(),
            )); ?>
        </div>
        <p>
            <label><strong><?php esc_html_e('Combine targeting filters with', 'ai-eshop-optimizer'); ?></strong></label>
            <span class="description" style="display:block;">
                <label class="aieo-dmm-choice"><input type="radio" name="rule_operator" value="AND" checked> <strong>AND</strong> — <?php esc_html_e('every set targeting filter must match (brand AND category AND need AND specific-products)', 'ai-eshop-optimizer'); ?></label>
            </span>
            <span class="description" style="display:block;">
                <label class="aieo-dmm-choice"><input type="radio" name="rule_operator" value="OR"> <strong>OR</strong> — <?php esc_html_e('any non-empty targeting filter that hits qualifies the product', 'ai-eshop-optimizer'); ?></label>
            </span>
        </p>
        <div class="aieo-dmm-grid">
            <p>
                <label><?php esc_html_e('From', 'ai-eshop-optimizer'); ?></label>
                <input type="date" name="date_from">
            </p>
            <p>
                <label><?php esc_html_e('To', 'ai-eshop-optimizer'); ?></label>
                <input type="date" name="date_to">
            </p>
            <p>
                <label><?php esc_html_e('Notes', 'ai-eshop-optimizer'); ?></label>
                <input type="text" name="notes" class="regular-text" placeholder="<?php esc_attr_e('e.g. Q4 promo', 'ai-eshop-optimizer'); ?>">
            </p>
            <p>
                <label class="aieo-dmm-choice" style="margin-top:24px;">
                    <input type="checkbox" name="enabled" checked value="1">
                    <?php esc_html_e('Enabled', 'ai-eshop-optimizer'); ?>
                </label>
            </p>
        </div>

        <details style="margin:14px 0;">
            <summary style="cursor:pointer;font-weight:600;color:#1f2937;"><?php esc_html_e('Show exclusions ▾', 'ai-eshop-optimizer'); ?></summary>
            <p class="description" style="margin:6px 0 8px;">
                <?php esc_html_e('Negative filters — when the cart contains any product matching one of these, the discount does NOT apply (overrides the positive targeting above). Leave empty to apply no exclusions.', 'ai-eshop-optimizer'); ?>
            </p>
            <div class="aieo-dmm-grid">
                <p>
                    <label><?php esc_html_e('Excluded brands', 'ai-eshop-optimizer'); ?></label>
                    <select name="excluded_brand_ids[]" multiple class="aieo-dmm-brand-select regular-text"></select>
                </p>
                <p>
                    <label><?php esc_html_e('Excluded categories', 'ai-eshop-optimizer'); ?></label>
                    <select name="excluded_category_ids[]" multiple class="aieo-dmm-category-select regular-text"></select>
                </p>
                <p>
                    <label><?php esc_html_e('Excluded needs', 'ai-eshop-optimizer'); ?></label>
                    <select name="excluded_need_ids[]" multiple class="aieo-dmm-need-select regular-text"></select>
                </p>
            </div>
            <div style="margin-top:10px;">
                <?php echo AIEO_DMM_Product_Picker::render_field(array(
                    'name'     => 'excluded_product_ids',
                    'mode'     => 'exclude',
                    'label'    => __('Excluded specific products', 'ai-eshop-optimizer'),
                    'help'     => __('When the cart contains ANY of these products, the discount does NOT apply (overrides the positive targeting above). Variations roll up to their parent.', 'ai-eshop-optimizer'),
                    'selected' => isset($edit_excluded_product_ids) ? $edit_excluded_product_ids : array(),
                )); ?>
            </div>
        </details>

        <!-- ============================================================
             Type-specific actionable section — DIFFERS per offer type.
             For discounts: Discount % + Application scope.
             ============================================================ -->
        <h3 style="margin:24px 0 6px;"><?php esc_html_e('Discount terms', 'ai-eshop-optimizer'); ?></h3>
        <p class="description" style="margin:0 0 8px;">
            <?php esc_html_e('What gets discounted, and by how much. Differs from gift offers (which choose a gift product) and free-shipping rules (which choose a shipping action).', 'ai-eshop-optimizer'); ?>
        </p>
        <div class="aieo-dmm-grid">
            <p>
                <label><?php esc_html_e('Discount %', 'ai-eshop-optimizer'); ?></label>
                <input type="number" name="percent" step="0.01" min="0.01" max="99.99" required placeholder="10.00">
            </p>
            <p>
                <label><?php esc_html_e('Application scope', 'ai-eshop-optimizer'); ?></label>
                <select name="application_scope">
                    <option value="targeted"><?php esc_html_e('Apply to matching items only', 'ai-eshop-optimizer'); ?></option>
                    <option value="whole_cart"><?php esc_html_e('Apply to the whole cart', 'ai-eshop-optimizer'); ?></option>
                </select>
                <span class="description"><?php esc_html_e('"Matching items only" = current behaviour. "Whole cart" = "spend €50 on MUA, get 10% off everything" promos.', 'ai-eshop-optimizer'); ?></span>
            </p>
        </div>

        <p class="submit">
            <button type="submit" class="button button-primary" data-action="aieo_dmm_brand_discount_save">
                <?php esc_html_e('Save discount', 'ai-eshop-optimizer'); ?>
            </button>
        </p>
    </form>
</div>

<div class="aieo-dmm-section">
    <h3><?php esc_html_e('Current product discounts', 'ai-eshop-optimizer'); ?>
        <span class="count" id="aieo-dmm-brand-discount-count">(<?php echo (int) count($discounts); ?>)</span>
    </h3>

    <table class="widefat striped aieo-table" id="aieo-dmm-brand-discounts-table"
           <?php if (empty($discounts)) echo 'style="display:none;"'; ?>>
        <thead>
            <tr>
                <th><?php esc_html_e('Label', 'ai-eshop-optimizer'); ?></th>
                <th><?php esc_html_e('Brand', 'ai-eshop-optimizer'); ?></th>
                <th><?php esc_html_e('Categories', 'ai-eshop-optimizer'); ?></th>
                <th><?php esc_html_e('Needs', 'ai-eshop-optimizer'); ?></th>
                <th><?php esc_html_e('Op', 'ai-eshop-optimizer'); ?></th>
                <th><?php esc_html_e('%', 'ai-eshop-optimizer'); ?></th>
                <th><?php esc_html_e('From', 'ai-eshop-optimizer'); ?></th>
                <th><?php esc_html_e('To', 'ai-eshop-optimizer'); ?></th>
                <th><?php esc_html_e('Enabled', 'ai-eshop-optimizer'); ?></th>
                <th><?php esc_html_e('Notes', 'ai-eshop-optimizer'); ?></th>
                <th></th>
            </tr>
        </thead>
        <tbody id="aieo-dmm-brand-discount-rows">
            <?php foreach ($discounts as $d) : ?>
                <tr data-id="<?php echo (int) $d['id']; ?>">
                    <td>
                        <?php if (!empty($d['label'])) : ?>
                            <strong><?php echo esc_html($d['label']); ?></strong>
                        <?php else : ?>
                            <em class="description">—</em>
                        <?php endif; ?>
                    </td>
                    <td>
                        <?php if (!empty($d['brand_label'])) : ?>
                            <?php echo esc_html($d['brand_label']); ?>
                            <code>#<?php echo (int) $d['brand_term_id']; ?></code>
                        <?php else : ?>
                            <em class="description"><?php esc_html_e('(any)', 'ai-eshop-optimizer'); ?></em>
                        <?php endif; ?>
                    </td>
                    <td>
                        <?php if (!empty($d['category_labels'])) : ?>
                            <?php echo esc_html(implode(', ', $d['category_labels'])); ?>
                        <?php else : ?>
                            <em class="description"><?php esc_html_e('(any)', 'ai-eshop-optimizer'); ?></em>
                        <?php endif; ?>
                    </td>
                    <td>
                        <?php if (!empty($d['need_labels'])) : ?>
                            <?php echo esc_html(implode(', ', $d['need_labels'])); ?>
                        <?php else : ?>
                            <em class="description"><?php esc_html_e('(any)', 'ai-eshop-optimizer'); ?></em>
                        <?php endif; ?>
                    </td>
                    <td><strong><?php echo esc_html($d['rule_operator']); ?></strong></td>
                    <td><?php echo esc_html(number_format((float) $d['percent'], 2)); ?></td>
                    <td><?php echo esc_html((string) ($d['date_from'] ?? '')); ?></td>
                    <td><?php echo esc_html((string) ($d['date_to'] ?? '')); ?></td>
                    <td><?php echo !empty($d['enabled']) ? '✔' : '—'; ?></td>
                    <td><?php echo esc_html((string) ($d['notes'] ?? '')); ?></td>
                    <td>
                        <button type="button" class="button button-small aieo-dmm-delete-row" data-action="aieo_dmm_brand_discount_delete">
                            <?php esc_html_e('Delete', 'ai-eshop-optimizer'); ?>
                        </button>
                    </td>
                </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
    <p class="description" id="aieo-dmm-brand-discounts-empty"
       <?php if (!empty($discounts)) echo 'style="display:none;"'; ?>>
        <?php esc_html_e('No product discounts defined yet.', 'ai-eshop-optimizer'); ?>
    </p>
</div>

<?php

?>
<div class="aieo-dmm-section">
    <h2><?php esc_html_e('Προσφορά του μήνα — CSV import', 'ai-eshop-optimizer'); ?></h2>
    <p class="description">
        <?php esc_html_e('Bulk-schedule monthly sale prices from a CSV file. Required columns:', 'ai-eshop-optimizer'); ?>
        <code>Date_From</code>, <code>Date_to</code>, <code>SKU</code>, <code>Percentage_Discount</code>.
        <?php esc_html_e('Date format DD/MM/YYYY (or YYYY-MM-DD). Empty Date_From → starts immediately. Empty Date_to → no end date. Each imported product is tagged with a batch id so the "Προσφορά του Μήνα" badge replaces the standard sale badge for the duration of the offer.', 'ai-eshop-optimizer'); ?>
    </p>

    <p>
        <strong><?php esc_html_e('Currently tagged products:', 'ai-eshop-optimizer'); ?></strong>
        <code><?php echo (int) $monthly_offer_count; ?></code>
        <?php esc_html_e('total', 'ai-eshop-optimizer'); ?>,
        <code><?php echo (int) $monthly_offer_active; ?></code>
        <?php esc_html_e('currently in active sale window', 'ai-eshop-optimizer'); ?>.
    </p>

    <form id="aieo-dmm-csv-form" enctype="multipart/form-data" class="aieo-dmm-form">
        <p>
            <label><?php esc_html_e('CSV file', 'ai-eshop-optimizer'); ?></label>
            <input type="file" name="csv_file" accept=".csv" required>
        </p>
        <p class="submit">
            <button type="submit" class="button button-primary" id="aieo-dmm-csv-upload-btn">
                <?php esc_html_e('Upload &amp; process', 'ai-eshop-optimizer'); ?>
            </button>
            <button type="button" class="button" id="aieo-dmm-csv-clear-btn" style="margin-left:8px;">
                <?php esc_html_e('Clear all monthly offers', 'ai-eshop-optimizer'); ?>
            </button>
            <span id="aieo-dmm-csv-status" style="margin-left:12px;"></span>
        </p>
        <div id="aieo-dmm-csv-progress-wrap" style="display:none;margin-top:8px;">
            <div style="background:#e5e7eb;height:8px;border-radius:4px;overflow:hidden;">
                <div id="aieo-dmm-csv-progress-bar" style="background:#4caf50;height:100%;width:0;transition:width 200ms ease;"></div>
            </div>
            <p class="description" id="aieo-dmm-csv-progress-text" style="margin-top:6px;"></p>
        </div>
        <details id="aieo-dmm-csv-errors-wrap" style="display:none;margin-top:8px;">
            <summary><?php esc_html_e('Errors (most recent)', 'ai-eshop-optimizer'); ?></summary>
            <pre id="aieo-dmm-csv-errors" style="white-space:pre-wrap;font-size:11px;background:#fff8e1;padding:8px;border:1px solid #fbc02d;max-height:240px;overflow:auto;"></pre>
        </details>
    </form>

    <h3 style="margin-top:18px;"><?php esc_html_e('CSV format example', 'ai-eshop-optimizer'); ?></h3>
    <pre style="background:#f6f7f7;padding:8px;border-left:3px solid #c3c4c7;font-size:12px;">Date_From,Date_to,SKU,Percentage_Discount
31/10/2025,31/12/2025,PROD-001,15.5
01/11/2025,,PROD-VAR-001,20.0
,15/02/2026,PROD-002,10.0</pre>
</div>

<?php

?>
<div class="aieo-dmm-section">
    <h2><?php esc_html_e('NEW product threshold', 'ai-eshop-optimizer'); ?></h2>
    <p class="description">
        <?php
        printf(
            
            esc_html__('Number of days after publication during which a product counts as "new". The unified badge renderer reads this value to drive the NEW family. Label, colours, and surfaces moved to %s.', 'ai-eshop-optimizer'),
            '<a href="' . esc_url(admin_url('admin.php?page=ai-eshop-dmm&dmm_tab=badges')) . '"><code>?dmm_tab=badges</code></a>'
        );
        ?>
    </p>

    <form id="aieo-dmm-badge-form" class="aieo-dmm-form">
        <p>
            <label><?php esc_html_e('Days since publication', 'ai-eshop-optimizer'); ?></label>
            <input type="number" name="new_product_days" min="0" max="3650" step="1" class="small-text"
                   value="<?php echo (int) $new_product_days; ?>">
            <span class="description"><?php esc_html_e('Set 0 to disable the NEW badge entirely.', 'ai-eshop-optimizer'); ?></span>
        </p>
        <p class="submit">
            <button type="submit" class="button button-primary" id="aieo-dmm-badge-save-btn">
                <?php esc_html_e('Save', 'ai-eshop-optimizer'); ?>
            </button>
            <span id="aieo-dmm-badge-status" style="margin-left:12px;"></span>
        </p>
    </form>
</div>

<!-- ── Lowest-price (EU Omnibus) sale message ───────────────────────── -->
<div class="aieo-dmm-section">
    <h2><?php esc_html_e('Lowest-price (sale) message', 'ai-eshop-optimizer'); ?></h2>
    <p class="description" style="max-width:820px;">
        <?php esc_html_e('EU Omnibus: on products that are ON SALE, show the lowest price before the reduction. Edit the rich-text message + the info tooltip here, then position the message anywhere in the product info column from Storefront Display → Dashboard. The token {lowest_price} is replaced with the formatted price.', 'ai-eshop-optimizer'); ?>
    </p>
    <form id="aieo-dmm-lowest-price-form">
        <table class="form-table">
            <tr>
                <th scope="row"><?php esc_html_e('Enable', 'ai-eshop-optimizer'); ?></th>
                <td>
                    <label><input type="checkbox" name="lowest_price_message_enabled" value="1" <?php checked( (bool) AIEO_DMM_Settings::get('lowest_price_message_enabled', false) ); ?>> <?php esc_html_e('Show this message on on-sale products', 'ai-eshop-optimizer'); ?></label>
                    <p class="description"><?php esc_html_e('Off by default. When on, the message appears on every on-sale product (position it from Storefront Display → Dashboard).', 'ai-eshop-optimizer'); ?></p>
                </td>
            </tr>
            <tr>
                <th scope="row"><?php esc_html_e('Message', 'ai-eshop-optimizer'); ?></th>
                <td>
                    <?php
                    wp_editor(
                        (string) AIEO_DMM_Settings::get('lowest_price_message_text', ''),
                        'aieo_lowest_price_message_text',
                        array(
                            'textarea_name' => 'lowest_price_message_text',
                            'media_buttons' => false,
                            'teeny'         => true,
                            'textarea_rows' => 4,
                            'quicktags'     => true,
                        )
                    );
                    ?>
                    <p class="description"><?php esc_html_e('Rich text (links + basic formatting; scripts stripped). Use {lowest_price} where the price should appear.', 'ai-eshop-optimizer'); ?></p>
                </td>
            </tr>
            <tr>
                <th scope="row"><?php esc_html_e('Info tooltip', 'ai-eshop-optimizer'); ?></th>
                <td>
                    <textarea name="lowest_price_tooltip_text" rows="3" class="large-text"><?php echo esc_textarea((string) AIEO_DMM_Settings::get('lowest_price_tooltip_text', '')); ?></textarea>
                    <p class="description"><?php esc_html_e('Shown when the shopper hovers the info icon. Leave blank to hide the icon.', 'ai-eshop-optimizer'); ?></p>
                </td>
            </tr>
            <tr>
                <th scope="row"><?php esc_html_e('Font size', 'ai-eshop-optimizer'); ?></th>
                <td>
                    <input type="text" name="lowest_price_message_font_size" value="<?php echo esc_attr((string) AIEO_DMM_Settings::get('lowest_price_message_font_size', '0.75rem')); ?>" style="max-width:130px;" placeholder="0.75rem">
                    <p class="description"><?php esc_html_e('Any CSS size — e.g. 0.75rem, 12px, 0.9em. Absolute units (rem / px) are recommended so the message does not inherit the larger theme size. Default 0.75rem.', 'ai-eshop-optimizer'); ?></p>
                </td>
            </tr>
        </table>
        <p class="submit">
            <button type="submit" class="button button-primary" id="aieo-dmm-lowest-price-save"><?php esc_html_e('Save message', 'ai-eshop-optimizer'); ?></button>
            <span id="aieo-dmm-lowest-price-status" style="margin-left:12px;font-weight:600;"></span>
        </p>
    </form>
</div>

<!-- ── Product price / sale-price appearance ─────────────────────────── -->
<?php
$pa_layout  = (string) AIEO_DMM_Settings::get('price_layout', 'inline');
$pa_reg_fs  = (string) AIEO_DMM_Settings::get('price_regular_font_size', '');
$pa_reg_c   = (string) AIEO_DMM_Settings::get('price_regular_color', '');
$pa_sale_fs = (string) AIEO_DMM_Settings::get('price_sale_font_size', '');
$pa_sale_c  = (string) AIEO_DMM_Settings::get('price_sale_color', '');
$pa_bold    = (bool) AIEO_DMM_Settings::get('price_sale_bold', false);
$pa_reg_fs_m  = (string) AIEO_DMM_Settings::get('price_regular_font_size_mobile', '');
$pa_sale_fs_m = (string) AIEO_DMM_Settings::get('price_sale_font_size_mobile', '');
$pa_sep_on  = (bool) AIEO_DMM_Settings::get('price_separator_enabled', false);
$pa_sep_sp  = (string) AIEO_DMM_Settings::get('price_separator_spacing', '16px');
$pa_sep_th  = (string) AIEO_DMM_Settings::get('price_separator_thickness', '1px');
$pa_sep_c   = (string) AIEO_DMM_Settings::get('price_separator_color', '#e0e0e0');
$pa_ar_reg    = (string) AIEO_DMM_Settings::get('price_archive_regular_font_size', '');
$pa_ar_reg_m  = (string) AIEO_DMM_Settings::get('price_archive_regular_font_size_mobile', '');
$pa_ar_sale   = (string) AIEO_DMM_Settings::get('price_archive_sale_font_size', '');
$pa_ar_sale_m = (string) AIEO_DMM_Settings::get('price_archive_sale_font_size_mobile', '');
?>
<div class="aieo-dmm-section">
    <h2><?php esc_html_e('Price &amp; sale-price appearance', 'ai-eshop-optimizer'); ?></h2>
    <p class="description" style="max-width:820px;">
        <?php esc_html_e('Styles the product price block on single-product pages: the layout when on sale (regular + sale side by side, or stacked with the sale price on top) and the font size + colour of the regular (was) and sale (now) prices. Leave a size/colour blank to inherit the theme.', 'ai-eshop-optimizer'); ?>
    </p>
    <form id="aieo-dmm-price-appearance-form">
        <table class="form-table">
            <tr>
                <th scope="row"><?php esc_html_e('Layout (on sale)', 'ai-eshop-optimizer'); ?></th>
                <td>
                    <select name="price_layout">
                        <option value="inline" <?php selected($pa_layout, 'inline'); ?>><?php esc_html_e('Side by side (was — now)', 'ai-eshop-optimizer'); ?></option>
                        <option value="stacked_sale_first" <?php selected($pa_layout, 'stacked_sale_first'); ?>><?php esc_html_e('Stacked — sale price on top', 'ai-eshop-optimizer'); ?></option>
                        <option value="stacked_regular_first" <?php selected($pa_layout, 'stacked_regular_first'); ?>><?php esc_html_e('Stacked — regular price on top', 'ai-eshop-optimizer'); ?></option>
                    </select>
                </td>
            </tr>
            <tr>
                <th scope="row"><?php esc_html_e('Regular (was) price — font size', 'ai-eshop-optimizer'); ?></th>
                <td>
                    <label style="display:inline-block;margin-right:16px;"><span style="display:block;font-size:11px;color:#6b7280;"><?php esc_html_e('Desktop', 'ai-eshop-optimizer'); ?></span>
                        <input type="text" name="price_regular_font_size" value="<?php echo esc_attr($pa_reg_fs); ?>" placeholder="e.g. 1rem / 16px" style="max-width:150px;"></label>
                    <label style="display:inline-block;"><span style="display:block;font-size:11px;color:#6b7280;"><?php esc_html_e('Mobile', 'ai-eshop-optimizer'); ?></span>
                        <input type="text" name="price_regular_font_size_mobile" value="<?php echo esc_attr($pa_reg_fs_m); ?>" placeholder="e.g. 0.9rem" style="max-width:150px;"></label>
                </td>
            </tr>
            <tr>
                <th scope="row"><?php esc_html_e('Regular (was) price — colour', 'ai-eshop-optimizer'); ?></th>
                <td><input type="text" name="price_regular_color" value="<?php echo esc_attr($pa_reg_c); ?>" class="aieo-color" placeholder="#999999" style="max-width:160px;"></td>
            </tr>
            <tr>
                <th scope="row"><?php esc_html_e('Sale (now) price — font size', 'ai-eshop-optimizer'); ?></th>
                <td>
                    <label style="display:inline-block;margin-right:16px;"><span style="display:block;font-size:11px;color:#6b7280;"><?php esc_html_e('Desktop', 'ai-eshop-optimizer'); ?></span>
                        <input type="text" name="price_sale_font_size" value="<?php echo esc_attr($pa_sale_fs); ?>" placeholder="e.g. 1.4rem / 22px" style="max-width:150px;"></label>
                    <label style="display:inline-block;"><span style="display:block;font-size:11px;color:#6b7280;"><?php esc_html_e('Mobile', 'ai-eshop-optimizer'); ?></span>
                        <input type="text" name="price_sale_font_size_mobile" value="<?php echo esc_attr($pa_sale_fs_m); ?>" placeholder="e.g. 1.2rem" style="max-width:150px;"></label>
                </td>
            </tr>
            <tr>
                <th scope="row"><?php esc_html_e('Sale (now) price — colour', 'ai-eshop-optimizer'); ?></th>
                <td><input type="text" name="price_sale_color" value="<?php echo esc_attr($pa_sale_c); ?>" class="aieo-color" placeholder="#b41944" style="max-width:160px;"></td>
            </tr>
            <tr>
                <th scope="row"><?php esc_html_e('Bold the sale price', 'ai-eshop-optimizer'); ?></th>
                <td><label><input type="checkbox" name="price_sale_bold" value="1" <?php checked($pa_bold); ?>> <?php esc_html_e('Render the sale (current) price in bold', 'ai-eshop-optimizer'); ?></label></td>
            </tr>

            <tr><td colspan="2" style="padding:18px 0 4px;"><strong style="font-size:13px;"><?php esc_html_e('Separator line under the price (single product)', 'ai-eshop-optimizer'); ?></strong></td></tr>
            <tr>
                <th scope="row"><?php esc_html_e('Show separator line', 'ai-eshop-optimizer'); ?></th>
                <td><label><input type="checkbox" name="price_separator_enabled" value="1" <?php checked($pa_sep_on); ?>> <?php esc_html_e('Full-width thin line under the price.', 'ai-eshop-optimizer'); ?></label></td>
            </tr>
            <tr>
                <th scope="row"><?php esc_html_e('Line — spacing from price', 'ai-eshop-optimizer'); ?></th>
                <td><input type="text" name="price_separator_spacing" value="<?php echo esc_attr($pa_sep_sp); ?>" placeholder="16px" style="max-width:150px;"></td>
            </tr>
            <tr>
                <th scope="row"><?php esc_html_e('Line — thickness', 'ai-eshop-optimizer'); ?></th>
                <td><input type="text" name="price_separator_thickness" value="<?php echo esc_attr($pa_sep_th); ?>" placeholder="1px" style="max-width:150px;"></td>
            </tr>
            <tr>
                <th scope="row"><?php esc_html_e('Line — colour', 'ai-eshop-optimizer'); ?></th>
                <td><input type="text" name="price_separator_color" value="<?php echo esc_attr($pa_sep_c); ?>" class="aieo-color" placeholder="#e0e0e0" style="max-width:160px;"></td>
            </tr>

            <tr><td colspan="2" style="padding:18px 0 4px;"><strong style="font-size:13px;"><?php esc_html_e('Archive (product cards) price — font size', 'ai-eshop-optimizer'); ?></strong></td></tr>
            <tr>
                <th scope="row"><?php esc_html_e('Regular price — font size', 'ai-eshop-optimizer'); ?></th>
                <td>
                    <label style="display:inline-block;margin-right:16px;"><span style="display:block;font-size:11px;color:#6b7280;"><?php esc_html_e('Desktop', 'ai-eshop-optimizer'); ?></span>
                        <input type="text" name="price_archive_regular_font_size" value="<?php echo esc_attr($pa_ar_reg); ?>" placeholder="e.g. 0.9rem" style="max-width:150px;"></label>
                    <label style="display:inline-block;"><span style="display:block;font-size:11px;color:#6b7280;"><?php esc_html_e('Mobile', 'ai-eshop-optimizer'); ?></span>
                        <input type="text" name="price_archive_regular_font_size_mobile" value="<?php echo esc_attr($pa_ar_reg_m); ?>" placeholder="e.g. 0.8rem" style="max-width:150px;"></label>
                </td>
            </tr>
            <tr>
                <th scope="row"><?php esc_html_e('Sale price — font size', 'ai-eshop-optimizer'); ?></th>
                <td>
                    <label style="display:inline-block;margin-right:16px;"><span style="display:block;font-size:11px;color:#6b7280;"><?php esc_html_e('Desktop', 'ai-eshop-optimizer'); ?></span>
                        <input type="text" name="price_archive_sale_font_size" value="<?php echo esc_attr($pa_ar_sale); ?>" placeholder="e.g. 1rem" style="max-width:150px;"></label>
                    <label style="display:inline-block;"><span style="display:block;font-size:11px;color:#6b7280;"><?php esc_html_e('Mobile', 'ai-eshop-optimizer'); ?></span>
                        <input type="text" name="price_archive_sale_font_size_mobile" value="<?php echo esc_attr($pa_ar_sale_m); ?>" placeholder="e.g. 0.9rem" style="max-width:150px;"></label>
                </td>
            </tr>
        </table>
        <p class="submit">
            <button type="submit" class="button button-primary" id="aieo-dmm-price-appearance-save"><?php esc_html_e('Save price appearance', 'ai-eshop-optimizer'); ?></button>
            <span id="aieo-dmm-price-appearance-status" style="margin-left:12px;font-weight:600;"></span>
        </p>
    </form>
</div>
<script>
(function () {
    var nonce   = <?php echo wp_json_encode(wp_create_nonce(AIEO_DMM::NONCE_ACTION)); ?>;
    var ajaxurl = <?php echo wp_json_encode(admin_url('admin-ajax.php')); ?>;
    var f = document.getElementById('aieo-dmm-price-appearance-form');
    var s = document.getElementById('aieo-dmm-price-appearance-status');
    if (f) {
        f.addEventListener('submit', function (e) {
            e.preventDefault();
            var fd = new FormData(f);
            fd.set('action', 'aieo_dmm_save_price_appearance');
            fd.set('nonce', nonce);
            if (s) { s.style.color = '#6b7280'; s.textContent = <?php echo wp_json_encode(__('Saving…', 'ai-eshop-optimizer')); ?>; }
            fetch(ajaxurl, { method: 'POST', body: fd, credentials: 'same-origin' })
                .then(function (r) { return r.json(); })
                .then(function (j) {
                    if (!s) { return; }
                    if (j && j.success) { s.style.color = '#15803d'; s.textContent = <?php echo wp_json_encode(__('Saved ✓', 'ai-eshop-optimizer')); ?>; }
                    else { s.style.color = '#b91c1c'; s.textContent = <?php echo wp_json_encode(__('Save failed.', 'ai-eshop-optimizer')); ?>; }
                })
                .catch(function () { if (s) { s.style.color = '#b91c1c'; s.textContent = 'Network error.'; } });
        });
    }
})();
</script>

<script>
(function () {
    var nonce = <?php echo wp_json_encode(wp_create_nonce(AIEO_DMM::NONCE_ACTION)); ?>;
    var ajaxurl = <?php echo wp_json_encode(admin_url('admin-ajax.php')); ?>;

    // ── Lowest-price (Omnibus) message save ────────────────────────────
    var lpForm   = document.getElementById('aieo-dmm-lowest-price-form');
    var lpStatus = document.getElementById('aieo-dmm-lowest-price-status');
    if (lpForm) {
        lpForm.addEventListener('submit', function (e) {
            e.preventDefault();
            try { if (window.tinyMCE) { tinyMCE.triggerSave(); } } catch (err) {}
            var fd = new FormData(lpForm);
            fd.set('action', 'aieo_dmm_save_lowest_price_message');
            fd.set('nonce', nonce);
            if (lpStatus) { lpStatus.style.color = '#6b7280'; lpStatus.textContent = <?php echo wp_json_encode(__('Saving…', 'ai-eshop-optimizer')); ?>; }
            fetch(ajaxurl, { method: 'POST', body: fd, credentials: 'same-origin' })
                .then(function (r) { return r.json(); })
                .then(function (j) {
                    if (!lpStatus) { return; }
                    if (j && j.success) { lpStatus.style.color = '#15803d'; lpStatus.textContent = <?php echo wp_json_encode(__('Saved ✓', 'ai-eshop-optimizer')); ?>; }
                    else { lpStatus.style.color = '#b91c1c'; lpStatus.textContent = <?php echo wp_json_encode(__('Save failed.', 'ai-eshop-optimizer')); ?>; }
                })
                .catch(function () { if (lpStatus) { lpStatus.style.color = '#b91c1c'; lpStatus.textContent = 'Network error.'; } });
        });
    }

    // ── CSV upload + batch processor ───────────────────────────────────
    var form    = document.getElementById('aieo-dmm-csv-form');
    var statusEl= document.getElementById('aieo-dmm-csv-status');
    var barWrap = document.getElementById('aieo-dmm-csv-progress-wrap');
    var bar     = document.getElementById('aieo-dmm-csv-progress-bar');
    var barText = document.getElementById('aieo-dmm-csv-progress-text');
    var errWrap = document.getElementById('aieo-dmm-csv-errors-wrap');
    var errBox  = document.getElementById('aieo-dmm-csv-errors');
    var clearBtn= document.getElementById('aieo-dmm-csv-clear-btn');

    function setProgress(pct, processed, total, success) {
        barWrap.style.display = 'block';
        bar.style.width = pct + '%';
        barText.textContent = pct + '%  —  '
            + processed + '/' + total + '  '
            + '(<?php echo esc_js(__('successful', 'ai-eshop-optimizer')); ?>: ' + success + ')';
    }

    function processBatch(batchId, total) {
        var fd = new FormData();
        fd.set('action', 'aieo_dmm_csv_process_batch');
        fd.set('nonce', nonce);
        fd.set('batch_id', batchId);
        fd.set('batch_size', '15');
        fetch(ajaxurl, { method: 'POST', body: fd, credentials: 'same-origin' })
            .then(function (r) { return r.json(); })
            .then(function (j) {
                if (!j || !j.success) {
                    statusEl.textContent = '<?php echo esc_js(__('Batch failed', 'ai-eshop-optimizer')); ?>: ' + (j && j.data && j.data.message || '');
                    return;
                }
                var d = j.data;
                setProgress(d.percentage, d.processed, d.total, d.success);
                if (d.errors && d.errors.length) {
                    errWrap.style.display = 'block';
                    errBox.textContent = d.errors.join('\n');
                }
                if (!d.is_done) {
                    processBatch(batchId, total);
                } else {
                    statusEl.textContent = '<?php echo esc_js(__('Done.', 'ai-eshop-optimizer')); ?>';
                    setTimeout(function () { window.location.reload(); }, 1200);
                }
            })
            .catch(function () { statusEl.textContent = '<?php echo esc_js(__('Network error.', 'ai-eshop-optimizer')); ?>'; });
    }

    if (form) {
        form.addEventListener('submit', function (e) {
            e.preventDefault();
            var fd = new FormData(form);
            fd.set('action', 'aieo_dmm_csv_upload');
            fd.set('nonce', nonce);
            statusEl.textContent = '<?php echo esc_js(__('Uploading…', 'ai-eshop-optimizer')); ?>';
            errWrap.style.display = 'none';
            barWrap.style.display = 'none';
            fetch(ajaxurl, { method: 'POST', body: fd, credentials: 'same-origin' })
                .then(function (r) { return r.json(); })
                .then(function (j) {
                    if (!j || !j.success) {
                        statusEl.textContent = '<?php echo esc_js(__('Upload failed', 'ai-eshop-optimizer')); ?>: ' + (j && j.data && j.data.message || '');
                        return;
                    }
                    statusEl.textContent = '<?php echo esc_js(__('Processing…', 'ai-eshop-optimizer')); ?>';
                    setProgress(0, 0, j.data.total, 0);
                    processBatch(j.data.batch_id, j.data.total);
                })
                .catch(function () { statusEl.textContent = '<?php echo esc_js(__('Network error.', 'ai-eshop-optimizer')); ?>'; });
        });
    }

    if (clearBtn) {
        clearBtn.addEventListener('click', function () {
            if (!window.confirm('<?php echo esc_js(__('Remove every monthly-offer sale price + tag? This will clear sale prices on currently-tagged products.', 'ai-eshop-optimizer')); ?>')) return;
            statusEl.textContent = '<?php echo esc_js(__('Clearing…', 'ai-eshop-optimizer')); ?>';
            var fd = new FormData();
            fd.set('action', 'aieo_dmm_csv_clear');
            fd.set('nonce', nonce);
            fetch(ajaxurl, { method: 'POST', body: fd, credentials: 'same-origin' })
                .then(function (r) { return r.json(); })
                .then(function (j) {
                    if (j && j.success) {
                        statusEl.textContent = j.data.message;
                        setTimeout(function () { window.location.reload(); }, 800);
                    } else {
                        statusEl.textContent = '<?php echo esc_js(__('Failed.', 'ai-eshop-optimizer')); ?>';
                    }
                });
        });
    }

    // ── Badge settings save ───────────────────────────────────────────
    var bForm  = document.getElementById('aieo-dmm-badge-form');
    var bStatus= document.getElementById('aieo-dmm-badge-status');
    if (bForm) {
        bForm.addEventListener('submit', function (e) {
            e.preventDefault();
            var fd = new FormData(bForm);
            fd.set('action', 'aieo_dmm_save_badge_settings');
            fd.set('nonce', nonce);
            bStatus.textContent = '<?php echo esc_js(__('Saving…', 'ai-eshop-optimizer')); ?>';
            fetch(ajaxurl, { method: 'POST', body: fd, credentials: 'same-origin' })
                .then(function (r) { return r.json(); })
                .then(function (j) {
                    bStatus.textContent = j && j.success
                        ? '<?php echo esc_js(__('Saved ✓', 'ai-eshop-optimizer')); ?>'
                        : '<?php echo esc_js(__('Save failed.', 'ai-eshop-optimizer')); ?>';
                });
        });
    }
})();
</script>
