<?php

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

$enabled         = !empty($settings['side_cart_enabled']);
$open_on_add     = !empty($settings['side_cart_open_on_add']);
$quick_view_on   = !empty($settings['side_cart_quick_view_enabled']);

$bar_items_config = array();
$chat_desktop_pos = 'left';

if ( ! class_exists( 'AIEO_Side_Cart_Display' ) && defined( 'AIEO_DIR' ) && file_exists( AIEO_DIR . 'includes/class-aieo-side-cart-display.php' ) ) {
    require_once AIEO_DIR . 'includes/class-aieo-side-cart-display.php';
}
if ( class_exists( 'AIEO_Side_Cart_Display' ) ) {
    $disp = AIEO_Side_Cart_Display::instance();
    $bar_items_config = $disp->resolve_bar_items_config();
    $chat_desktop_pos = $disp->resolve_chat_desktop_position();
}
$heading         = isset($settings['side_cart_heading'])      ? (string) $settings['side_cart_heading']      : '';
$left_heading    = isset($settings['side_cart_left_heading']) ? (string) $settings['side_cart_left_heading'] : '';
$border_enabled  = !isset($settings['side_cart_card_border_enabled']) ? true : !empty($settings['side_cart_card_border_enabled']);
$border_color    = isset($settings['side_cart_card_border_color']) ? (string) $settings['side_cart_card_border_color'] : '#c0a37b';
$border_hover    = isset($settings['side_cart_card_border_hover']) ? (string) $settings['side_cart_card_border_hover'] : '#a88a63';

$theme_accent = '#c0a37b';
if (function_exists('wp_get_global_settings')) {
    $aieo_pal = wp_get_global_settings(array('color', 'palette'));
    $aieo_pal = (isset($aieo_pal['theme']) || isset($aieo_pal['custom']) || isset($aieo_pal['default']))
        ? array_merge((array) ($aieo_pal['theme'] ?? array()), (array) ($aieo_pal['custom'] ?? array()), (array) ($aieo_pal['default'] ?? array()))
        : (array) $aieo_pal;
    foreach ($aieo_pal as $aieo_c) {
        if (is_array($aieo_c) && ($aieo_c['slug'] ?? '') === 'accent' && !empty($aieo_c['color'])) { $theme_accent = (string) $aieo_c['color']; break; }
    }
}
$accent_custom    = !empty($settings['side_cart_accent_color']);
$accent_color     = $accent_custom ? (string) $settings['side_cart_accent_color'] : $theme_accent;
$reco_title_color = !empty($settings['side_cart_reco_title_color']) ? (string) $settings['side_cart_reco_title_color'] : $accent_color;

$mbar_custom     = !empty($settings['side_cart_mbar_custom']);
$mbar_height     = isset($settings['side_cart_mbar_height']) ? (int) $settings['side_cart_mbar_height'] : 58;
$mbar_bg         = (isset($settings['side_cart_mbar_bg'])       && $settings['side_cart_mbar_bg']       !== '') ? (string) $settings['side_cart_mbar_bg']       : '#f46767';
$mbar_icon       = (isset($settings['side_cart_mbar_icon'])     && $settings['side_cart_mbar_icon']     !== '') ? (string) $settings['side_cart_mbar_icon']     : '#ffffff';
$mbar_icon_active = (isset($settings['side_cart_mbar_icon_active']) && $settings['side_cart_mbar_icon_active'] !== '') ? (string) $settings['side_cart_mbar_icon_active'] : '#f46767';
$mbar_badge_bg   = (isset($settings['side_cart_mbar_badge_bg']) && $settings['side_cart_mbar_badge_bg'] !== '') ? (string) $settings['side_cart_mbar_badge_bg'] : '#1f2937';
$mbar_badge_fg   = (isset($settings['side_cart_mbar_badge_fg']) && $settings['side_cart_mbar_badge_fg'] !== '') ? (string) $settings['side_cart_mbar_badge_fg'] : '#ffffff';
$mbar_bubble     = !isset($settings['side_cart_mbar_cart_bubble']) ? true : !empty($settings['side_cart_mbar_cart_bubble']);
$mbar_glass      = !empty($settings['side_cart_mbar_glass']);
$mbar_opacity    = isset($settings['side_cart_mbar_opacity']) ? (int) $settings['side_cart_mbar_opacity'] : 70;
$mbar_blur       = isset($settings['side_cart_mbar_blur']) ? (int) $settings['side_cart_mbar_blur'] : 12;
$mbar_sel_enable = !empty($settings['side_cart_mbar_sel_enable']);
$mbar_sel_def    = array('bg' => '#ffffff', 'fg' => '#1f2937', 'bc' => '#ffffff');
$mbar_sel        = array();
foreach (array('nav', 'search', 'chat', 'consent', 'cart') as $sslug) {
    foreach (array('bg', 'fg', 'bc') as $spart) {
        $skey = 'side_cart_mbar_' . $sslug . '_sel_' . $spart;
        $mbar_sel[$sslug][$spart] = (isset($settings[$skey]) && $settings[$skey] !== '') ? (string) $settings[$skey] : $mbar_sel_def[$spart];
    }
}
$fs_threshold = isset($settings['free_shipping']['free_shipping_threshold'])
    ? (float) $settings['free_shipping']['free_shipping_threshold']
    : 0.0;

$label_fields = array(
    'side_cart_tab_bag'        => array(__('Shopping bag tab',    'ai-eshop-optimizer'), __('SHOPPING BAG',                'ai-eshop-optimizer')),
    'side_cart_tab_viewed'     => array(__('Recently viewed tab', 'ai-eshop-optimizer'), __('RECENTLY VIEWED',             'ai-eshop-optimizer')),
    'side_cart_continue'       => array(__('Continue shopping',   'ai-eshop-optimizer'), __('CONTINUE SHOPPING',           'ai-eshop-optimizer')),
    'side_cart_maylike_title'  => array(__('You may also like…',  'ai-eshop-optimizer'), __('YOU MAY ALSO LIKE...',        'ai-eshop-optimizer')),
    'side_cart_subtotal_label' => array(__('Subtotal label',      'ai-eshop-optimizer'), __('SUBTOTAL:',                    'ai-eshop-optimizer')),
    'side_cart_coupon_link'    => array(__('Coupon toggle link',  'ai-eshop-optimizer'), __('Have a Coupon?',              'ai-eshop-optimizer')),
    'side_cart_btn_cart'       => array(__('Cart button',         'ai-eshop-optimizer'), __('CART',                         'ai-eshop-optimizer')),
    'side_cart_btn_checkout'   => array(__('Checkout button',     'ai-eshop-optimizer'), __('CHECKOUT',                     'ai-eshop-optimizer')),
    'side_cart_btn_addbag'     => array(__('Add-to-bag button',   'ai-eshop-optimizer'), __('ADD TO BAG',                  'ai-eshop-optimizer')),
    'side_cart_rv_empty'       => array(__('Recently viewed empty state', 'ai-eshop-optimizer'), __('No recently viewed products.', 'ai-eshop-optimizer')),
    'side_cart_quick_view_label' => array(__('Quick view button',  'ai-eshop-optimizer'), __('Discover it',                  'ai-eshop-optimizer')),
    'side_cart_qv_view_product'  => array(__('Quick view "view product" link', 'ai-eshop-optimizer'), __('View product details', 'ai-eshop-optimizer')),
    'side_cart_in_cart_label'    => array(__('Already-in-bag indicator', 'ai-eshop-optimizer'), __('✓ IN BAG',                  'ai-eshop-optimizer')),
);
?>
<div class="aieo-dmm-section">
    <h2><?php esc_html_e('Floating side cart (mini-cart)', 'ai-eshop-optimizer'); ?></h2>
    <p class="description">
        <?php esc_html_e('Rey-style floating trigger + two-column side panel: shopping bag on the right, "you might like" recommendations + free-shipping progress on the left. Optimistic quantity updates with a 500 ms debounced AJAX keep it instant, and cart HTML is cached per cart_hash in the WC session (30 s TTL) to avoid recomputing on every open.', 'ai-eshop-optimizer'); ?>
    </p>

    <div class="aieo-dmm-callout">
        <strong><?php esc_html_e('Important', 'ai-eshop-optimizer'); ?>:</strong>
        <?php esc_html_e('If you keep om-free-shipping active with its own mini-cart enabled, you will get two panels. Disable om-free-shipping (or its mini-cart toggle) once this side cart is live.', 'ai-eshop-optimizer'); ?>
    </div>

    <form id="aieo-dmm-side-cart-form" class="aieo-dmm-form">
        <table class="form-table">
            <tr>
                <th><?php esc_html_e('Enabled', 'ai-eshop-optimizer'); ?></th>
                <td>
                    <label class="aieo-dmm-choice">
                        <input type="checkbox" name="side_cart_enabled" value="1" <?php checked($enabled); ?>>
                        <?php esc_html_e('Render the floating trigger + side cart on the frontend', 'ai-eshop-optimizer'); ?>
                    </label>
                </td>
            </tr>
            <tr>
                <th><?php esc_html_e('Open on add to cart', 'ai-eshop-optimizer'); ?></th>
                <td>
                    <label class="aieo-dmm-choice">
                        <input type="checkbox" name="side_cart_open_on_add" value="1" <?php checked($open_on_add); ?>>
                        <?php esc_html_e('Auto-open the side cart panel every time a product is added to the cart', 'ai-eshop-optimizer'); ?>
                    </label>
                    <p class="description">
                        <?php esc_html_e('When off, the cart counter just updates silently. When on, the panel slides open so the shopper can review what they just added.', 'ai-eshop-optimizer'); ?>
                    </p>
                </td>
            </tr>
            <tr>
                <th><?php esc_html_e('Quick view on archives', 'ai-eshop-optimizer'); ?></th>
                <td>
                    <label class="aieo-dmm-choice">
                        <input type="checkbox" name="side_cart_quick_view_enabled" value="1" <?php checked($quick_view_on); ?>>
                        <?php esc_html_e('Show a "Discover it" button under each shop-loop product', 'ai-eshop-optimizer'); ?>
                    </label>
                    <p class="description">
                        <?php esc_html_e('Clicking it opens the side cart in quick-view mode: large image, title, price, and an add-to-cart button — all pulled from the archive card already on the page (no extra round-trip). The button label is configurable below under "Visible labels".', 'ai-eshop-optimizer'); ?>
                    </p>
                </td>
            </tr>
            <tr>
                <th><?php esc_html_e('Bottom bar items (mobile)', 'ai-eshop-optimizer'); ?></th>
                <td>
                    <p class="description" style="margin:0 0 8px;">
                        <?php esc_html_e('Drag to reorder. Toggle each item to show or hide it. The order applies to the mobile bottom bar; on desktop only the cart trigger and the AI Chat launcher are visible (the rest of the desktop UI carries the navigator + search in the header).', 'ai-eshop-optimizer'); ?>
                    </p>
                    <style>
                        .aieo-sc-bar-items-list { margin: 0; padding: 0; list-style: none; max-width: 560px; }
                        .aieo-sc-bar-items-list li {
                            display: flex; align-items: center; gap: 10px;
                            padding: 8px 10px;
                            border: 1px solid #e5e7eb;
                            border-radius: 6px;
                            margin: 0 0 6px;
                            background: #fff;
                        }
                        .aieo-sc-bar-items-list .aieo-sc-bar-drag {
                            cursor: grab; color: #9ca3af; font-weight: 700; letter-spacing: 1px;
                        }
                        .aieo-sc-bar-items-list .aieo-sc-bar-label { flex: 1 1 auto; font-weight: 500; }
                        .aieo-sc-bar-items-placeholder {
                            visibility: visible !important;
                            background: #fef3c7;
                            border: 1px dashed #f59e0b;
                            border-radius: 6px;
                            margin: 0 0 6px;
                            height: 42px;
                        }
                        .aieo-sc-bar-items-list li.ui-sortable-helper {
                            background: #fff !important;
                            box-shadow: 0 8px 22px rgba(0,0,0,0.12);
                        }
                    </style>
                    <ul id="aieo-sc-bar-items-list" class="aieo-sc-bar-items-list">
                        <?php foreach ($bar_items_config as $item):
                            $slug    = (string) $item['slug'];
                            $label   = (string) $item['label'];
                            $is_on   = !empty($item['enabled']);
                        ?>
                        <li data-slug="<?php echo esc_attr($slug); ?>">
                            <span class="aieo-sc-bar-drag">⋮⋮</span>
                            <span class="aieo-sc-bar-label"><?php echo esc_html($label); ?></span>
                            <label style="display:inline-flex;align-items:center;gap:6px;color:#6a6a6a;">
                                <input type="checkbox" class="aieo-sc-bar-enabled" <?php checked($is_on); ?>>
                                <span><?php esc_html_e('Visible', 'ai-eshop-optimizer'); ?></span>
                            </label>
                        </li>
                        <?php endforeach; ?>
                    </ul>
                    <input type="hidden" name="side_cart_bar_items" id="aieo-sc-bar-items-input" value="">
                </td>
            </tr>
            <tr>
                <th><?php esc_html_e('Mobile bottom bar — styling', 'ai-eshop-optimizer'); ?></th>
                <td>
                    <p class="description" style="margin:0 0 10px;">
                        <?php esc_html_e('Make the mobile sticky bottom bar look the same on any theme. These controls apply to mobile only — desktop keeps its own floating circle. The cart-count colours here can differ from desktop.', 'ai-eshop-optimizer'); ?>
                    </p>
                    <label class="aieo-dmm-choice" style="display:block;margin-bottom:10px;">
                        <input type="checkbox" name="side_cart_mbar_custom" value="1" <?php checked($mbar_custom); ?>>
                        <?php esc_html_e('Use custom colours (make the bar theme-independent)', 'ai-eshop-optimizer'); ?>
                        <span class="description" style="font-weight:normal;display:block;margin-left:24px;font-size:12px;">
                            <?php esc_html_e('When off, the bar inherits your theme’s accent (background) and text colours — the current look. Turn on to paint the colours chosen below regardless of theme.', 'ai-eshop-optimizer'); ?>
                        </span>
                    </label>
                    <div style="display:flex;flex-wrap:wrap;gap:14px 22px;align-items:center;font-size:13px;margin:0 0 12px;">
                        <label style="display:inline-flex;align-items:center;gap:6px;">
                            <span><?php esc_html_e('Bar height', 'ai-eshop-optimizer'); ?></span>
                            <input type="number" name="side_cart_mbar_height" min="40" max="96" value="<?php echo (int) $mbar_height; ?>" style="width:64px;">px
                        </label>
                        <label style="display:inline-flex;align-items:center;gap:6px;">
                            <span><?php esc_html_e('Bar background', 'ai-eshop-optimizer'); ?></span>
                            <input type="color" name="side_cart_mbar_bg" value="<?php echo esc_attr($mbar_bg); ?>">
                        </label>
                        <label style="display:inline-flex;align-items:center;gap:6px;">
                            <span><?php esc_html_e('Icon colour', 'ai-eshop-optimizer'); ?></span>
                            <input type="color" name="side_cart_mbar_icon" value="<?php echo esc_attr($mbar_icon); ?>">
                        </label>
                        <label style="display:inline-flex;align-items:center;gap:6px;" title="<?php esc_attr_e('The icon colour of the active/pressed button (e.g. Search while its panel is open) — a cue that tapping again closes it. Applies to menu, search, AI chat, cookies and cart.', 'ai-eshop-optimizer'); ?>">
                            <span><?php esc_html_e('Selected icon colour', 'ai-eshop-optimizer'); ?></span>
                            <input type="color" name="side_cart_mbar_icon_active" value="<?php echo esc_attr($mbar_icon_active); ?>">
                        </label>
                        <label style="display:inline-flex;align-items:center;gap:6px;">
                            <span><?php esc_html_e('Cart-count number', 'ai-eshop-optimizer'); ?></span>
                            <input type="color" name="side_cart_mbar_badge_fg" value="<?php echo esc_attr($mbar_badge_fg); ?>">
                        </label>
                        <label style="display:inline-flex;align-items:center;gap:6px;">
                            <span><?php esc_html_e('Cart-count circle', 'ai-eshop-optimizer'); ?></span>
                            <input type="color" name="side_cart_mbar_badge_bg" value="<?php echo esc_attr($mbar_badge_bg); ?>">
                        </label>
                    </div>
                    <label class="aieo-dmm-choice" style="display:block;margin-bottom:6px;">
                        <input type="checkbox" name="side_cart_mbar_glass" value="1" <?php checked($mbar_glass); ?>>
                        <?php esc_html_e('Glass effect (transparent bar with backdrop blur)', 'ai-eshop-optimizer'); ?>
                        <span class="description" style="font-weight:normal;display:block;margin-left:24px;font-size:12px;">
                            <?php esc_html_e('Renders the bar background semi-transparent so page content shows through, with a frosted-glass blur. Uses the bar background colour above (or your theme accent).', 'ai-eshop-optimizer'); ?>
                        </span>
                    </label>
                    <div style="display:flex;flex-wrap:wrap;gap:14px 22px;align-items:center;font-size:13px;margin:0 0 12px;">
                        <label style="display:inline-flex;align-items:center;gap:6px;">
                            <span><?php esc_html_e('Opacity', 'ai-eshop-optimizer'); ?></span>
                            <input type="number" name="side_cart_mbar_opacity" min="0" max="100" value="<?php echo (int) $mbar_opacity; ?>" style="width:64px;">%
                        </label>
                        <label style="display:inline-flex;align-items:center;gap:6px;">
                            <span><?php esc_html_e('Blur', 'ai-eshop-optimizer'); ?></span>
                            <input type="number" name="side_cart_mbar_blur" min="0" max="40" value="<?php echo (int) $mbar_blur; ?>" style="width:64px;">px
                        </label>
                    </div>
                    <label class="aieo-dmm-choice" style="display:block;">
                        <input type="checkbox" name="side_cart_mbar_cart_bubble" value="1" <?php checked($mbar_bubble); ?>>
                        <?php esc_html_e('When only the cart icon is enabled, show it as a floating bubble (like desktop) instead of a full-width bar', 'ai-eshop-optimizer'); ?>
                        <span class="description" style="font-weight:normal;display:block;margin-left:24px;font-size:12px;">
                            <?php esc_html_e('Gives the clean desktop-style circle and fixes the single-icon left-alignment. With two or more icons enabled the full bar is always used; a single non-cart icon is centred.', 'ai-eshop-optimizer'); ?>
                        </span>
                    </label>
                    <label class="aieo-dmm-choice" style="display:block;margin-top:14px;">
                        <input type="checkbox" name="side_cart_mbar_sel_enable" value="1" <?php checked($mbar_sel_enable); ?>>
                        <?php esc_html_e('Style the selected (active) option', 'ai-eshop-optimizer'); ?>
                        <span class="description" style="font-weight:normal;display:block;margin-left:24px;font-size:12px;">
                            <?php esc_html_e('Highlight each option while its panel/drawer is open — background, text/icon and border colour per option.', 'ai-eshop-optimizer'); ?>
                        </span>
                    </label>
                    <table class="form-table" style="margin-top:4px;max-width:520px;">
                        <thead><tr>
                            <th style="width:120px;text-align:left;"><?php esc_html_e('Option', 'ai-eshop-optimizer'); ?></th>
                            <th style="text-align:left;"><?php esc_html_e('Background', 'ai-eshop-optimizer'); ?></th>
                            <th style="text-align:left;"><?php esc_html_e('Text / icon', 'ai-eshop-optimizer'); ?></th>
                            <th style="text-align:left;"><?php esc_html_e('Border', 'ai-eshop-optimizer'); ?></th>
                        </tr></thead>
                        <tbody>
                        <?php
                        $sel_labels = array(
                            'nav'     => __('Navigator', 'ai-eshop-optimizer'),
                            'search'  => __('Search', 'ai-eshop-optimizer'),
                            'chat'    => __('AI Chat', 'ai-eshop-optimizer'),
                            'consent' => __('Cookie settings', 'ai-eshop-optimizer'),
                            'cart'    => __('Cart', 'ai-eshop-optimizer'),
                        );
                        foreach ($sel_labels as $sslug => $slabel): ?>
                            <tr>
                                <td><?php echo esc_html($slabel); ?></td>
                                <td><input type="color" name="side_cart_mbar_<?php echo esc_attr($sslug); ?>_sel_bg" value="<?php echo esc_attr($mbar_sel[$sslug]['bg']); ?>"></td>
                                <td><input type="color" name="side_cart_mbar_<?php echo esc_attr($sslug); ?>_sel_fg" value="<?php echo esc_attr($mbar_sel[$sslug]['fg']); ?>"></td>
                                <td><input type="color" name="side_cart_mbar_<?php echo esc_attr($sslug); ?>_sel_bc" value="<?php echo esc_attr($mbar_sel[$sslug]['bc']); ?>"></td>
                            </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                </td>
            </tr>
            <tr>
                <th><?php esc_html_e('AI Chat — desktop position', 'ai-eshop-optimizer'); ?></th>
                <td>
                    <select name="side_cart_chat_desktop_position">
                        <option value="left"  <?php selected($chat_desktop_pos, 'left');  ?>><?php esc_html_e('Bottom-left (symmetric to cart)', 'ai-eshop-optimizer'); ?></option>
                        <option value="above" <?php selected($chat_desktop_pos, 'above'); ?>><?php esc_html_e('Stacked above cart (same right edge)', 'ai-eshop-optimizer'); ?></option>
                    </select>
                    <p class="description">
                        <?php esc_html_e('Where the AI Chat launcher sits on desktop. Same 56×56 circle as the cart trigger; "above" stacks them with a 20px gap. Only takes effect when "AI Chat" is enabled in the bar items list above.', 'ai-eshop-optimizer'); ?>
                    </p>
                </td>
            </tr>
            <tr>
                <th><?php esc_html_e('Card border', 'ai-eshop-optimizer'); ?></th>
                <td>
                    <label class="aieo-dmm-choice" style="display:block;margin-bottom:8px;">
                        <input type="checkbox" name="side_cart_card_border_enabled" value="1" <?php checked($border_enabled); ?>>
                        <?php esc_html_e('Show a 1px border around recommendation / favorites / recently-viewed cards', 'ai-eshop-optimizer'); ?>
                    </label>
                    <label style="display:inline-flex;align-items:center;gap:8px;margin-right:18px;">
                        <span><?php esc_html_e('Border colour', 'ai-eshop-optimizer'); ?></span>
                        <input type="color" name="side_cart_card_border_color" value="<?php echo esc_attr($border_color); ?>">
                        <code style="font-size:11px;color:#6a6a6a;"><?php echo esc_html($border_color); ?></code>
                    </label>
                    <label style="display:inline-flex;align-items:center;gap:8px;">
                        <span><?php esc_html_e('Hover colour', 'ai-eshop-optimizer'); ?></span>
                        <input type="color" name="side_cart_card_border_hover" value="<?php echo esc_attr($border_hover); ?>">
                        <code style="font-size:11px;color:#6a6a6a;"><?php echo esc_html($border_hover); ?></code>
                    </label>
                    <p class="description"><?php esc_html_e('Default: brand gold (matches the active tab underline + CHECKOUT pill) with a darker tan on hover. Pick any colour or disable for a borderless flat-card look.', 'ai-eshop-optimizer'); ?></p>
                </td>
            </tr>
            <tr>
                <th><?php esc_html_e('Accent colours', 'ai-eshop-optimizer'); ?></th>
                <td>
                    <label class="aieo-dmm-choice" style="display:block;margin-bottom:8px;">
                        <input type="checkbox" name="side_cart_accent_custom" value="1" <?php checked($accent_custom); ?>>
                        <?php esc_html_e('Use custom accent colours (otherwise the side-cart follows your theme accent automatically)', 'ai-eshop-optimizer'); ?>
                    </label>
                    <label style="display:inline-flex;align-items:center;gap:8px;margin-right:18px;">
                        <span><?php esc_html_e('Accent', 'ai-eshop-optimizer'); ?></span>
                        <input type="color" name="side_cart_accent_color" value="<?php echo esc_attr($accent_color); ?>">
                        <code style="font-size:11px;color:#6a6a6a;"><?php echo esc_html($accent_color); ?></code>
                    </label>
                    <label style="display:inline-flex;align-items:center;gap:8px;">
                        <span><?php esc_html_e('Recommendations title', 'ai-eshop-optimizer'); ?></span>
                        <input type="color" name="side_cart_reco_title_color" value="<?php echo esc_attr($reco_title_color); ?>">
                        <code style="font-size:11px;color:#6a6a6a;"><?php echo esc_html($reco_title_color); ?></code>
                    </label>
                    <p class="description"><?php printf(esc_html__('“Accent” drives the active tab underline, the count badge, the free-shipping progress bar and the gift-quantity label. “Recommendations title” is the left-column “You may like” heading (defaults to the accent). Leave the box unticked to follow your theme accent (%s).', 'ai-eshop-optimizer'), esc_html($theme_accent)); ?></p>
                </td>
            </tr>
            <tr>
                <th><?php esc_html_e('Action buttons (CART / CHECKOUT)', 'ai-eshop-optimizer'); ?></th>
                <td>
                    <?php
                    
                    
                    $btn_show_cart  = !isset($settings['side_cart_show_cart_btn']) ? true : !empty($settings['side_cart_show_cart_btn']);
                    $btn_show_save  = !empty($settings['side_cart_show_save_btn']);
                    $btn_save_label = isset($settings['side_cart_btn_save']) ? (string) $settings['side_cart_btn_save'] : '';
                    $btn_defs = array(
                        'cart'     => array('label' => __('CART button', 'ai-eshop-optimizer'),     'bg' => '#e9e6e2', 'color' => '#1a1a1a', 'radius' => 24),
                        'checkout' => array('label' => __('CHECKOUT button', 'ai-eshop-optimizer'), 'bg' => '#c0a37b', 'color' => '#ffffff', 'radius' => 24),
                        'save'     => array('label' => __('SAVE button (Saved Carts)', 'ai-eshop-optimizer'), 'bg' => '#e9e6e2', 'color' => '#1a1a1a', 'radius' => 24),
                    );
                    $border_styles = array(
                        'none'   => __('None (no border)', 'ai-eshop-optimizer'),
                        'solid'  => __('Solid', 'ai-eshop-optimizer'),
                        'dashed' => __('Dashed', 'ai-eshop-optimizer'),
                        'dotted' => __('Dotted', 'ai-eshop-optimizer'),
                        'double' => __('Double', 'ai-eshop-optimizer'),
                    );
                    ?>
                    <input type="hidden" name="button_settings_form" value="1">
                    <label class="aieo-dmm-choice" style="display:block;margin-bottom:12px;">
                        <input type="checkbox" name="side_cart_show_cart_btn" value="1" <?php checked($btn_show_cart); ?>>
                        <?php esc_html_e('Show the CART button', 'ai-eshop-optimizer'); ?>
                        <span class="description" style="font-weight:normal;display:block;margin-left:24px;font-size:12px;">
                            <?php esc_html_e('Disable when your floating cart trigger already provides the cart-page link — keeps just CHECKOUT in the footer, spanning the full width.', 'ai-eshop-optimizer'); ?>
                        </span>
                    </label>

                    <label class="aieo-dmm-choice" style="display:block;margin-bottom:8px;">
                        <input type="checkbox" name="side_cart_show_save_btn" value="1" <?php checked($btn_show_save); ?>>
                        <?php esc_html_e('Show the SAVE button (Saved Carts) — takes the CART button’s slot', 'ai-eshop-optimizer'); ?>
                        <span class="description" style="font-weight:normal;display:block;margin-left:24px;font-size:12px;">
                            <?php esc_html_e('Lets shoppers save & share their cart straight from the side-cart (auto-copies the share link). Style it below.', 'ai-eshop-optimizer'); ?>
                        </span>
                    </label>
                    <p style="margin:0 0 12px 24px;font-size:13px;">
                        <label><?php esc_html_e('SAVE button text', 'ai-eshop-optimizer'); ?>
                            <input type="text" name="side_cart_btn_save" value="<?php echo esc_attr($btn_save_label); ?>" placeholder="<?php esc_attr_e('Save cart', 'ai-eshop-optimizer'); ?>" style="margin-left:6px;width:200px;">
                        </label>
                    </p>

                    <?php foreach ($btn_defs as $which => $def):
                        $bg     = isset($settings['side_cart_btn_' . $which . '_bg'])           ? (string) $settings['side_cart_btn_' . $which . '_bg']           : '';
                        $color  = isset($settings['side_cart_btn_' . $which . '_color'])        ? (string) $settings['side_cart_btn_' . $which . '_color']        : '';
                        $bstyle = isset($settings['side_cart_btn_' . $which . '_border_style']) ? (string) $settings['side_cart_btn_' . $which . '_border_style'] : 'none';
                        $bcolor = isset($settings['side_cart_btn_' . $which . '_border_color']) ? (string) $settings['side_cart_btn_' . $which . '_border_color'] : '';
                        $bwidth = isset($settings['side_cart_btn_' . $which . '_border_width']) ? (int)    $settings['side_cart_btn_' . $which . '_border_width'] : 0;
                        $radius = isset($settings['side_cart_btn_' . $which . '_radius'])       ? (int)    $settings['side_cart_btn_' . $which . '_radius']       : (int) $def['radius'];
                    ?>
                        <fieldset style="border:1px solid #e0e0e0;border-radius:6px;padding:10px 14px;margin-bottom:10px;">
                            <legend style="font-weight:600;padding:0 6px;"><?php echo esc_html($def['label']); ?></legend>
                            <div style="display:flex;flex-wrap:wrap;gap:14px 24px;align-items:center;font-size:13px;">
                                <label style="display:inline-flex;align-items:center;gap:6px;">
                                    <span><?php esc_html_e('Background', 'ai-eshop-optimizer'); ?></span>
                                    <input type="color" name="side_cart_btn_<?php echo esc_attr($which); ?>_bg" value="<?php echo esc_attr($bg !== '' ? $bg : $def['bg']); ?>">
                                </label>
                                <label style="display:inline-flex;align-items:center;gap:6px;">
                                    <span><?php esc_html_e('Text colour', 'ai-eshop-optimizer'); ?></span>
                                    <input type="color" name="side_cart_btn_<?php echo esc_attr($which); ?>_color" value="<?php echo esc_attr($color !== '' ? $color : $def['color']); ?>">
                                </label>
                                <label style="display:inline-flex;align-items:center;gap:6px;">
                                    <span><?php esc_html_e('Border', 'ai-eshop-optimizer'); ?></span>
                                    <select name="side_cart_btn_<?php echo esc_attr($which); ?>_border_style">
                                        <?php foreach ($border_styles as $val => $label): ?>
                                            <option value="<?php echo esc_attr($val); ?>" <?php selected($bstyle, $val); ?>><?php echo esc_html($label); ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </label>
                                <label style="display:inline-flex;align-items:center;gap:6px;">
                                    <span><?php esc_html_e('Border width', 'ai-eshop-optimizer'); ?></span>
                                    <input type="number" name="side_cart_btn_<?php echo esc_attr($which); ?>_border_width" min="0" max="8" value="<?php echo (int) $bwidth; ?>" style="width:60px;">px
                                </label>
                                <label style="display:inline-flex;align-items:center;gap:6px;">
                                    <span><?php esc_html_e('Border colour', 'ai-eshop-optimizer'); ?></span>
                                    <input type="color" name="side_cart_btn_<?php echo esc_attr($which); ?>_border_color" value="<?php echo esc_attr($bcolor !== '' ? $bcolor : ($bg !== '' ? $bg : $def['bg'])); ?>">
                                </label>
                                <label style="display:inline-flex;align-items:center;gap:6px;">
                                    <span><?php esc_html_e('Corner radius', 'ai-eshop-optimizer'); ?></span>
                                    <input type="number" name="side_cart_btn_<?php echo esc_attr($which); ?>_radius" min="0" max="48" value="<?php echo (int) $radius; ?>" style="width:60px;">px
                                </label>
                            </div>
                        </fieldset>
                    <?php endforeach; ?>
                    <p class="description"><?php esc_html_e('Defaults: CART = neutral grey (#e9e6e2 / #1a1a1a), CHECKOUT = brand gold (#c0a37b / #ffffff). Border style "None" omits the border entirely; any other style uses the chosen width + colour.', 'ai-eshop-optimizer'); ?></p>
                </td>
            </tr>
            <tr>
                <th><?php esc_html_e('Favorites / wishlist', 'ai-eshop-optimizer'); ?></th>
                <td>
                    <p class="description">
                        <?php
                        if (!function_exists('is_plugin_active')) {
                            require_once ABSPATH . 'wp-admin/includes/plugin.php';
                        }
                        $ppe_active  = is_plugin_active('om-product-page-essentials/om-product-page-essentials.php');
                        $aieo_table  = $GLOBALS['wpdb']->prefix . 'aieo_wishlist';
                        $aieo_exists = (string) $GLOBALS['wpdb']->get_var($GLOBALS['wpdb']->prepare('SHOW TABLES LIKE %s', $aieo_table)) === $aieo_table;
                        ?>
                        <?php
                        printf(
                            
                            esc_html__('Side-cart Favorites tab persists to %1$s via the aieo_wishlist_toggle endpoint, sharing the %2$s cookie so toggles stay in sync with any other wishlist UI on the page.', 'ai-eshop-optimizer'),
                            '<code>' . esc_html($aieo_table) . '</code>',
                            '<code>woocommerce_items_in_cart_merchant_wishlist</code>'
                        );
                        ?>
                        <br>
                        <strong><?php esc_html_e('Schema:', 'ai-eshop-optimizer'); ?></strong>
                        <?php echo $aieo_exists
                            ? '<span style="color:#1f7a1f;">' . esc_html__('table is installed.', 'ai-eshop-optimizer') . '</span>'
                            : '<span style="color:#a33;">'   . esc_html__('table NOT installed yet — visit any frontend page or re-activate the plugin.', 'ai-eshop-optimizer') . '</span>'; ?>
                        <?php if ($ppe_active): ?>
                            <br>
                            <em><?php esc_html_e('OM Product Essentials wishlist is also active. During this Phase-1 migration, hearts toggled in the side cart are written to BOTH tables for safety. Phase 2 will retire the PPE module.', 'ai-eshop-optimizer'); ?></em>
                        <?php endif; ?>
                    </p>
                </td>
            </tr>
            <tr>
                <th><?php esc_html_e('Panel heading', 'ai-eshop-optimizer'); ?></th>
                <td>
                    <input type="text" name="side_cart_heading" class="large-text"
                           value="<?php echo esc_attr($heading); ?>"
                           placeholder="<?php esc_attr_e('Your Bag', 'ai-eshop-optimizer'); ?>">
                    <p class="description">
                        <?php esc_html_e('Top-right title of the slide-out panel. Leave empty for the default "Your Bag".', 'ai-eshop-optimizer'); ?>
                    </p>
                </td>
            </tr>
            <tr>
                <th><?php esc_html_e('Left column heading', 'ai-eshop-optimizer'); ?></th>
                <td>
                    <input type="text" name="side_cart_left_heading" class="large-text"
                           value="<?php echo esc_attr($left_heading); ?>"
                           placeholder="<?php esc_attr_e('You might like', 'ai-eshop-optimizer'); ?>">
                    <p class="description">
                        <?php esc_html_e('Small header shown above the recommendations carousel in the left column.', 'ai-eshop-optimizer'); ?>
                    </p>
                </td>
            </tr>
            <tr>
                <th><?php esc_html_e('Free shipping progress', 'ai-eshop-optimizer'); ?></th>
                <td>
                    <p>
                        <?php
                        printf(
                            
                            esc_html__('The progress bar at the top of the cart uses the threshold configured in the Free Shipping tab (currently %s). Messages also come from there.', 'ai-eshop-optimizer'),
                            '<strong>' . esc_html(wc_price($fs_threshold)) . '</strong>' 
                        );
                        ?>
                    </p>
                </td>
            </tr>
            <tr>
                <th><?php esc_html_e('Recommendations source', 'ai-eshop-optimizer'); ?></th>
                <td>
                    <p>
                        <?php esc_html_e('The "you might like" carousel pulls from the DMM product bundle endpoint (the same superset AJAX that powers single-product-page recommendations). The Recently Viewed tab reads from localStorage first, then falls back to the same bundle endpoint. No extra queries on panel open.', 'ai-eshop-optimizer'); ?>
                    </p>
                </td>
            </tr>
            <tr>
                <th colspan="2">
                    <h3 style="margin:18px 0 4px;"><?php esc_html_e('Visible labels', 'ai-eshop-optimizer'); ?></h3>
                    <p class="description" style="font-weight:normal;">
                        <?php esc_html_e('Override the wording shown to shoppers. Leave any field empty to use the default (which still goes through the translation files).', 'ai-eshop-optimizer'); ?>
                    </p>
                </th>
            </tr>
            <?php foreach ($label_fields as $key => $meta):
                $field_label    = $meta[0];
                $field_default  = $meta[1];
                $field_value    = isset($settings[$key]) ? (string) $settings[$key] : '';
            ?>
            <tr>
                <th><?php echo esc_html($field_label); ?></th>
                <td>
                    <input type="text" name="<?php echo esc_attr($key); ?>" class="regular-text"
                           value="<?php echo esc_attr($field_value); ?>"
                           placeholder="<?php echo esc_attr($field_default); ?>">
                </td>
            </tr>
            <?php endforeach; ?>
        </table>
        <p class="submit">
            <button type="submit" class="button button-primary" data-action="aieo_dmm_side_cart_save_settings">
                <?php esc_html_e('Save side cart settings', 'ai-eshop-optimizer'); ?>
            </button>
        </p>
    </form>
    <script>
    (function () {
        // Wire the bar-items sortable + populate the hidden input on
        // submit so the form serialise picks up the latest state.
        var listEl  = document.getElementById('aieo-sc-bar-items-list');
        var inputEl = document.getElementById('aieo-sc-bar-items-input');
        var formEl  = document.getElementById('aieo-dmm-side-cart-form');
        if (!listEl || !inputEl || !formEl) return;

        function readState() {
            var rows = [];
            listEl.querySelectorAll('li[data-slug]').forEach(function (li) {
                var cb = li.querySelector('.aieo-sc-bar-enabled');
                rows.push({
                    slug: li.getAttribute('data-slug') || '',
                    enabled: cb ? !!cb.checked : false
                });
            });
            return rows;
        }
        function syncInput() { inputEl.value = JSON.stringify(readState()); }

        // Initial population — covers the case where the user clicks
        // submit without dragging or toggling anything.
        syncInput();

        if (window.jQuery) {
            jQuery(function ($) {
                if (!$.fn.sortable) return;
                $(listEl).sortable({
                    handle: '.aieo-sc-bar-drag',
                    items: '> li',
                    placeholder: 'aieo-sc-bar-items-placeholder',
                    forcePlaceholderSize: true,
                    tolerance: 'pointer',
                    cursor: 'grabbing',
                    opacity: 0.85,
                    update: syncInput
                });
            });
        }
        listEl.addEventListener('change', function (e) {
            if (e.target && e.target.classList.contains('aieo-sc-bar-enabled')) {
                syncInput();
            }
        });
        // Belt + braces — re-sync just before submit, so any last-second
        // change is captured even if the change/sortable handlers missed.
        formEl.addEventListener('submit', syncInput, true);
    })();
    </script>
</div>

<div class="aieo-dmm-section">
    <h2><?php esc_html_e('How it works', 'ai-eshop-optimizer'); ?></h2>
    <ul class="aieo-dmm-bullets">
        <li>
            <strong><?php esc_html_e('Optimistic updates.', 'ai-eshop-optimizer'); ?></strong>
            <?php esc_html_e('Clicking +/- on a cart line updates the DOM and the progress bar instantly from a per-item cached unit price. The server AJAX is 500 ms debounced so rapid clicks collapse into a single request.', 'ai-eshop-optimizer'); ?>
        </li>
        <li>
            <strong><?php esc_html_e('400-byte response.', 'ai-eshop-optimizer'); ?></strong>
            <?php esc_html_e('The quantity AJAX returns just count + subtotal_raw + a gifts_changed flag. The server does not re-render the cart unless gift eligibility has changed.', 'ai-eshop-optimizer'); ?>
        </li>
        <li>
            <strong><?php esc_html_e('Session HTML cache.', 'ai-eshop-optimizer'); ?></strong>
            <?php esc_html_e('The full panel HTML is cached in the WC session keyed by WooCommerce cart_hash. Any cart change other than pure quantity edits (add, remove, coupon, clear) invalidates it automatically.', 'ai-eshop-optimizer'); ?>
        </li>
        <li>
            <strong><?php esc_html_e('Brand gifts compatible.', 'ai-eshop-optimizer'); ?></strong>
            <?php esc_html_e('Gift lines inherit the locked-quantity, hidden-remove-link treatment that the Brand Gifts module applies everywhere else.', 'ai-eshop-optimizer'); ?>
        </li>
        <li>
            <strong><?php esc_html_e('DMM recipe aware.', 'ai-eshop-optimizer'); ?></strong>
            <?php esc_html_e('Line prices, subtotal, and the free-shipping progress all respect the global stacking recipe when "Apply recipe to main price" is on in the Loyalty tab.', 'ai-eshop-optimizer'); ?>
        </li>
    </ul>
</div>
