<?php

if (!defined('ABSPATH')) { exit; }

$settings = AIEO_DMM_Settings::get_all();
$recipe = $settings['recipe'];
?>
<div class="aieo-dmm-section">
    <h2><?php esc_html_e('Global stacking recipe', 'ai-eshop-optimizer'); ?></h2>
    <p class="description">
        <?php esc_html_e('Decide how role price, brand discount, loyalty class and brand gift combine across the whole shop.', 'ai-eshop-optimizer'); ?>
    </p>
    <form id="aieo-dmm-recipe-form" class="aieo-dmm-form">
        <table class="form-table">
            <tr>
                <th><?php esc_html_e('Role pricing', 'ai-eshop-optimizer'); ?></th>
                <td>
                    <select name="recipe[role_pricing]">
                        <option value="active" <?php selected($recipe['role_pricing'], 'active'); ?>><?php esc_html_e('Active (role prices apply)', 'ai-eshop-optimizer'); ?></option>
                        <option value="off" <?php selected($recipe['role_pricing'], 'off'); ?>><?php esc_html_e('Off', 'ai-eshop-optimizer'); ?></option>
                    </select>
                </td>
            </tr>
            <tr>
                <th><?php esc_html_e('Brand discount', 'ai-eshop-optimizer'); ?></th>
                <td>
                    <select name="recipe[brand_discount]">
                        <option value="stack_multiplicative" <?php selected($recipe['brand_discount'], 'stack_multiplicative'); ?>><?php esc_html_e('Stack × (on role-adjusted)', 'ai-eshop-optimizer'); ?></option>
                        <option value="stack_additive" <?php selected($recipe['brand_discount'], 'stack_additive'); ?>><?php esc_html_e('Stack additively', 'ai-eshop-optimizer'); ?></option>
                        <option value="replace_role" <?php selected($recipe['brand_discount'], 'replace_role'); ?>><?php esc_html_e('Replace role price', 'ai-eshop-optimizer'); ?></option>
                        <option value="off" <?php selected($recipe['brand_discount'], 'off'); ?>><?php esc_html_e('Off', 'ai-eshop-optimizer'); ?></option>
                    </select>
                </td>
            </tr>
            <tr>
                <th><?php esc_html_e('Loyalty class', 'ai-eshop-optimizer'); ?></th>
                <td>
                    <select name="recipe[loyalty_class]">
                        <option value="stack_multiplicative" <?php selected($recipe['loyalty_class'], 'stack_multiplicative'); ?>><?php esc_html_e('Stack × (on role+brand)', 'ai-eshop-optimizer'); ?></option>
                        <option value="stack_additive" <?php selected($recipe['loyalty_class'], 'stack_additive'); ?>><?php esc_html_e('Stack additively', 'ai-eshop-optimizer'); ?></option>
                        <option value="replace_all" <?php selected($recipe['loyalty_class'], 'replace_all'); ?>><?php esc_html_e('Replace all other discounts', 'ai-eshop-optimizer'); ?></option>
                        <option value="off" <?php selected($recipe['loyalty_class'], 'off'); ?>><?php esc_html_e('Off', 'ai-eshop-optimizer'); ?></option>
                    </select>
                </td>
            </tr>
            <tr>
                <th><?php esc_html_e('Brand gift', 'ai-eshop-optimizer'); ?></th>
                <td>
                    <select name="recipe[brand_gift]">
                        <option value="over_and_above" <?php selected($recipe['brand_gift'], 'over_and_above'); ?>><?php esc_html_e('Over and above (in addition to %)', 'ai-eshop-optimizer'); ?></option>
                        <option value="off" <?php selected($recipe['brand_gift'], 'off'); ?>><?php esc_html_e('Off', 'ai-eshop-optimizer'); ?></option>
                    </select>
                </td>
            </tr>
            <tr>
                <th><?php esc_html_e('No-free-shipping gate', 'ai-eshop-optimizer'); ?></th>
                <td>
                    <select name="recipe[no_free_shipping_gate]">
                        <option value="hard" <?php selected($recipe['no_free_shipping_gate'], 'hard'); ?>><?php esc_html_e('Hard (remove free shipping when any excluded item in cart)', 'ai-eshop-optimizer'); ?></option>
                        <option value="soft" <?php selected($recipe['no_free_shipping_gate'], 'soft'); ?>><?php esc_html_e('Soft (keep rates; UI can warn)', 'ai-eshop-optimizer'); ?></option>
                        <option value="off" <?php selected($recipe['no_free_shipping_gate'], 'off'); ?>><?php esc_html_e('Off (no gate)', 'ai-eshop-optimizer'); ?></option>
                    </select>
                </td>
            </tr>
            <tr>
                <th colspan="2" style="padding-top:18px;">
                    <h3 style="margin:0;"><?php esc_html_e('Product-bundle delivery (performance)', 'ai-eshop-optimizer'); ?></h3>
                    <p class="description" style="font-weight:400; margin:4px 0 0;">
                        <?php esc_html_e('Controls how the single-product page fetches upsells, cross-sells, need-based and related products. Both modes use the same cache table keyed by (product_id, role_hash, locale, mode) — flipping the switch does NOT require a cache flush. Prices are always pre-computed and baked into the cached HTML.', 'ai-eshop-optimizer'); ?>
                    </p>
                </th>
            </tr>
            <tr>
                <th><?php esc_html_e('Bundle mode', 'ai-eshop-optimizer'); ?></th>
                <td>
                    <?php $bundle_mode = isset($settings['bundle_mode']) ? $settings['bundle_mode'] : 'full'; ?>
                    <label class="aieo-dmm-choice" style="display:block;margin-bottom:6px;">
                        <input type="radio" name="bundle_mode" value="full" <?php checked($bundle_mode, 'full'); ?>>
                        <strong>Full</strong> — <?php esc_html_e('one AJAX returns all 4 recommendation blocks PLUS variation data (feeds om-product-swatches). Fewest HTTP requests.', 'ai-eshop-optimizer'); ?>
                    </label>
                    <label class="aieo-dmm-choice" style="display:block;">
                        <input type="radio" name="bundle_mode" value="rec_only" <?php checked($bundle_mode, 'rec_only'); ?>>
                        <strong>Rec-only</strong> — <?php esc_html_e('one AJAX returns only the 4 recommendation blocks; om-product-swatches still fires its own variation AJAX. Cleaner separation.', 'ai-eshop-optimizer'); ?>
                    </label>
                    <p class="description" style="margin-top:6px;">
                        <?php esc_html_e('Recently-viewed is always handled separately with a localStorage-first strategy (zero AJAX when fresh).', 'ai-eshop-optimizer'); ?>
                    </p>
                </td>
            </tr>
            <tr>
                <th colspan="2" style="padding-top:18px;">
                    <h3 style="margin:0;"><?php esc_html_e('Pricing engine (performance)', 'ai-eshop-optimizer'); ?></h3>
                    <p class="description" style="font-weight:400; margin:4px 0 0;">
                        <?php esc_html_e('Controls how the DMM engine resolves brand/category/schedule/loyalty/NFS facts on every price request. Both modes produce identical prices — only the lookup strategy differs. Default is "Reactive" for a safe rollout. Flip to "Precomputed" on a server where you want to measure the hot-path savings. The switch takes effect on the next page load; FP rows are built lazily on first request.', 'ai-eshop-optimizer'); ?>
                    </p>
                </th>
            </tr>
            <tr>
                <th><?php esc_html_e('Pricing mode', 'ai-eshop-optimizer'); ?></th>
                <td>
                    <?php $pricing_mode = isset($settings['pricing_mode']) ? $settings['pricing_mode'] : 'reactive'; ?>
                    <label class="aieo-dmm-choice" style="display:block;margin-bottom:6px;">
                        <input type="radio" name="pricing_mode" value="reactive" <?php checked($pricing_mode, 'reactive'); ?>>
                        <strong>Reactive</strong> — <?php esc_html_e('walk active brand/category/schedule rules per request (cached via object cache). Same behaviour as Pass 1.', 'ai-eshop-optimizer'); ?>
                    </label>
                    <label class="aieo-dmm-choice" style="display:block;">
                        <input type="radio" name="pricing_mode" value="precomputed" <?php checked($pricing_mode, 'precomputed'); ?>>
                        <strong>Precomputed</strong> — <?php esc_html_e('read pre-stamped wp_aieo_dmm_product_fp / wp_aieo_dmm_user_fp rows. No taxonomy joins, no rule walks, no loyalty joins on the hot path. Required for future personalised / sequence-based discounts.', 'ai-eshop-optimizer'); ?>
                    </label>
                    <p class="description" style="margin-top:6px;">
                        <?php esc_html_e('Admin rule changes bump a single integer and never scan these tables; stale FP rows are recomputed one-at-a-time by the next reader.', 'ai-eshop-optimizer'); ?>
                    </p>
                </td>
            </tr>
            <tr>
                <th><?php esc_html_e('Apply recipe to main price', 'ai-eshop-optimizer'); ?></th>
                <td>
                    <?php $apply_main = !empty($settings['apply_recipe_to_main_price']); ?>
                    <label class="aieo-dmm-choice">
                        <input type="checkbox" name="apply_recipe_to_main_price" value="1" <?php checked($apply_main); ?>>
                        <?php esc_html_e('Make DMM discounts affect the main product-page price, cart line totals, and variation min/max — not only recommendation cards.', 'ai-eshop-optimizer'); ?>
                    </label>
                    <p class="description" style="margin-top:6px;">
                        <?php esc_html_e('When on, DMM hooks woocommerce_product_get_price at priority 20 (after om-role-pricing at 10), using its role-adjusted output as the base and applying brand / category / schedule / loyalty / personal steps on top. Memoised per (product, user, base) so double-application is impossible. Also extends woocommerce_get_variation_prices_hash so WC\'s variation price cache invalidates when the DMM recipe output would change. Leave off if you only want DMM pricing in recommendation cards and the NFS signal.', 'ai-eshop-optimizer'); ?>
                    </p>
                </td>
            </tr>
        </table>
        <p class="submit">
            <button type="submit" class="button button-primary" data-action="aieo_dmm_save_recipe">
                <?php esc_html_e('Save recipe', 'ai-eshop-optimizer'); ?>
            </button>
        </p>
    </form>
</div>

<div class="aieo-dmm-section">
    <h2><?php esc_html_e('Customer discount classes', 'ai-eshop-optimizer'); ?></h2>

    <form id="aieo-dmm-loyalty-class-form" class="aieo-dmm-form aieo-dmm-inline-form">
        <input type="hidden" name="id" value="0">
        <div class="aieo-dmm-grid">
            <p>
                <label><?php esc_html_e('Slug', 'ai-eshop-optimizer'); ?></label>
                <input type="text" name="slug" pattern="[a-z0-9_\-]+" required>
            </p>
            <p>
                <label><?php esc_html_e('Label', 'ai-eshop-optimizer'); ?></label>
                <input type="text" name="label" required class="regular-text">
            </p>
            <p>
                <label><?php esc_html_e('Extra discount %', 'ai-eshop-optimizer'); ?></label>
                <input type="number" step="0.01" min="0" max="99.99" name="extra_percent" required placeholder="5.00">
                <span class="description"><?php esc_html_e('On-top price discount for members in this class.', 'ai-eshop-optimizer'); ?></span>
            </p>
            <p>
                <label><?php esc_html_e('Points per currency unit', 'ai-eshop-optimizer'); ?></label>
                <input type="number" step="0.0001" min="0" name="points_per_currency" value="0" placeholder="1">
                <span class="description"><?php esc_html_e('E.g. 1 = 1 point per €1 of the order total. Awarded when the order transitions to "processing" or "completed".', 'ai-eshop-optimizer'); ?></span>
            </p>
            <p>
                <label class="aieo-dmm-choice" style="margin-top:24px;">
                    <input type="checkbox" name="enabled" value="1" checked>
                    <?php esc_html_e('Enabled', 'ai-eshop-optimizer'); ?>
                </label>
            </p>
        </div>
        <p>
            <label><?php esc_html_e('Description', 'ai-eshop-optimizer'); ?></label>
            <textarea name="description" rows="2" class="large-text"></textarea>
        </p>
        <p class="submit">
            <button type="submit" class="button button-primary" data-action="aieo_dmm_loyalty_class_save">
                <?php esc_html_e('Save class', 'ai-eshop-optimizer'); ?>
            </button>
        </p>
    </form>

    <table class="widefat striped aieo-table">
        <thead>
            <tr>
                <th><?php esc_html_e('Slug', 'ai-eshop-optimizer'); ?></th>
                <th><?php esc_html_e('Label', 'ai-eshop-optimizer'); ?></th>
                <th><?php esc_html_e('Extra %', 'ai-eshop-optimizer'); ?></th>
                <th><?php esc_html_e('Pts / unit', 'ai-eshop-optimizer'); ?></th>
                <th><?php esc_html_e('Enabled', 'ai-eshop-optimizer'); ?></th>
                <th></th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ((array) $classes as $c) : ?>
                <tr data-id="<?php echo (int) $c['id']; ?>">
                    <td><code><?php echo esc_html($c['slug']); ?></code></td>
                    <td><?php echo esc_html($c['label']); ?></td>
                    <td><?php echo esc_html(number_format((float) $c['extra_percent'], 2)); ?></td>
                    <td><?php echo esc_html(number_format((float) (isset($c['points_per_currency']) ? $c['points_per_currency'] : 0), 4)); ?></td>
                    <td><?php echo !empty($c['enabled']) ? '✔' : '—'; ?></td>
                    <td>
                        <button type="button" class="button button-small aieo-dmm-delete-row" data-action="aieo_dmm_loyalty_class_delete">
                            <?php esc_html_e('Delete', 'ai-eshop-optimizer'); ?>
                        </button>
                    </td>
                </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
</div>

<div class="aieo-dmm-section">
    <h2><?php esc_html_e('Assign a user', 'ai-eshop-optimizer'); ?></h2>
    <form id="aieo-dmm-loyalty-assign-form" class="aieo-dmm-form aieo-dmm-inline-form">
        <p>
            <select name="user_id" class="aieo-dmm-user-select regular-text" required></select>
            <select name="class_id" required>
                <option value=""><?php esc_html_e('— class —', 'ai-eshop-optimizer'); ?></option>
                <?php foreach ((array) $classes as $c) : ?>
                    <option value="<?php echo (int) $c['id']; ?>"><?php echo esc_html($c['label']); ?></option>
                <?php endforeach; ?>
            </select>
            <button type="submit" class="button button-primary" data-action="aieo_dmm_loyalty_assign_user">
                <?php esc_html_e('Assign', 'ai-eshop-optimizer'); ?>
            </button>
        </p>
    </form>

    <h3><?php esc_html_e('Bulk assignment by CSV', 'ai-eshop-optimizer'); ?></h3>
    <p class="description">
        <?php esc_html_e('CSV must include class_slug and one of user_email/user_login/user_id.', 'ai-eshop-optimizer'); ?>
    </p>
    <form id="aieo-dmm-loyalty-bulk-form" enctype="multipart/form-data" class="aieo-dmm-form">
        <p>
            <input type="file" name="csv_file" accept=".csv" required>
            <button type="submit" class="button"><?php esc_html_e('Upload & process', 'ai-eshop-optimizer'); ?></button>
        </p>
    </form>
    <div class="aieo-dmm-progress" id="aieo-dmm-loyalty-progress" style="display:none;">
        <div class="aieo-dmm-progress-bar"><span style="width:0%"></span></div>
        <p class="aieo-dmm-progress-text"></p>
    </div>
</div>

<div class="aieo-dmm-section">
    <h2><?php esc_html_e('Loyalty points', 'ai-eshop-optimizer'); ?></h2>

    <div class="aieo-dmm-card">
        <h3><?php esc_html_e('How points work', 'ai-eshop-optimizer'); ?></h3>
        <p class="description" style="margin:0;">
            <?php esc_html_e('Customers earn points automatically when a WooCommerce order moves to "processing" or "completed". The rate is class.points_per_currency × order total, summed across the customer\'s enabled classes. All point events (earn, spend, ERP import, manual adjust) land in a ledger — the balance is always the running SUM(delta) per user, never a stored counter, so it can\'t drift.', 'ai-eshop-optimizer'); ?>
        </p>
    </div>

    <div class="aieo-dmm-card">
        <h3><?php esc_html_e('ERP import contract', 'ai-eshop-optimizer'); ?></h3>
        <p class="description" style="margin:0 0 8px;">
            <?php esc_html_e('rooster-erp-connector\'s daily customer update brings over the back-office points balance. It should compute the delta it needs to push and call:', 'ai-eshop-optimizer'); ?>
        </p>
        <pre class="aieo-dmm-code" style="margin:0;">AIEO_DMM_Loyalty_Classes::add_points(
  $user_id,
  $delta_points,          // positive or negative
  'erp_import',
  'soft1:' . $erp_ref,    // idempotency key — duplicate refs are ignored
  $class_id = null,
  $notes = 'Daily SOFT1 sync'
);</pre>
        <p class="description" style="margin:8px 0 0;">
            <?php
            printf(
                
                esc_html__('We also emit %s after every successful points event so ERP-side mirrors can push deltas back to the back office (user_id, delta, new_balance, source, source_ref).', 'ai-eshop-optimizer'),
                '<code>aieo_dmm_loyalty_points_added</code>'
            );
            ?>
        </p>
    </div>

    <div class="aieo-dmm-card">
        <h3><?php esc_html_e('Manual adjustment', 'ai-eshop-optimizer'); ?></h3>
        <form id="aieo-dmm-loyalty-points-form" class="aieo-dmm-form aieo-dmm-inline-form">
            <div class="aieo-dmm-grid">
                <p>
                    <label><?php esc_html_e('User', 'ai-eshop-optimizer'); ?></label>
                    <select name="user_id" class="aieo-dmm-user-select regular-text" required></select>
                </p>
                <p>
                    <label><?php esc_html_e('Delta (signed)', 'ai-eshop-optimizer'); ?></label>
                    <input type="number" step="0.01" name="delta" required placeholder="100 or -50">
                    <span class="description"><?php esc_html_e('Positive = grant, negative = subtract / spend.', 'ai-eshop-optimizer'); ?></span>
                </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('Why (shown in the audit trail)', 'ai-eshop-optimizer'); ?>">
                </p>
            </div>
            <p class="submit">
                <button type="submit" class="button button-primary" data-action="aieo_dmm_loyalty_points_adjust">
                    <?php esc_html_e('Apply adjustment', 'ai-eshop-optimizer'); ?>
                </button>
            </p>
        </form>
    </div>
</div>

<div class="aieo-dmm-section">
    <h3><?php esc_html_e('Recent assignments', 'ai-eshop-optimizer'); ?></h3>
    <?php if (empty($assignments_sample)) : ?>
        <p><?php esc_html_e('No assignments yet.', 'ai-eshop-optimizer'); ?></p>
    <?php else : ?>
        <table class="widefat striped aieo-table">
            <thead>
                <tr>
                    <th><?php esc_html_e('User', 'ai-eshop-optimizer'); ?></th>
                    <th><?php esc_html_e('Class', 'ai-eshop-optimizer'); ?></th>
                    <th><?php esc_html_e('Assigned at', 'ai-eshop-optimizer'); ?></th>
                    <th></th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($assignments_sample as $a) : ?>
                    <tr>
                        <td><?php echo esc_html($a['user_label']); ?></td>
                        <td><?php echo esc_html($a['label']); ?> (<?php echo esc_html(number_format((float) $a['extra_percent'], 2)); ?>%)</td>
                        <td><?php echo esc_html($a['assigned_at']); ?></td>
                        <td>
                            <button type="button" class="button button-small aieo-dmm-unassign-loyalty"
                                    data-user-id="<?php echo (int) $a['user_id']; ?>"
                                    data-class-id="<?php echo (int) $a['class_id']; ?>">
                                <?php esc_html_e('Remove', 'ai-eshop-optimizer'); ?>
                            </button>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    <?php endif; ?>
</div>
