<?php
/**
 * GT BOGO Engine — Free Core Rule (Enterprise)
 * @package GT_BOGO_Engine
 * @since   3.11.0
 */
if (!defined('ABSPATH')) exit;
if (!current_user_can('manage_options')) return;

$is_pro  = function_exists('gt_bogo_has_pro') ? gt_bogo_has_pro() : false;
$message = ''; $message_type = '';
$version = defined('GT_BOGO_VERSION') ? GT_BOGO_VERSION : GT_BOGO_VERSION;

// ── Save Free Rule ────────────────────────────────────────────────────────
if (isset($_POST['gtbogo_save_free_rule']) && check_admin_referer('gtbogo_free_rule')) {
    global $wpdb;
    // Categories and products — stored as arrays of IDs
    $cats_raw  = sanitize_text_field( $_POST['rule_categories'] ?? '' );
    $prods_raw = sanitize_text_field( $_POST['rule_products']   ?? '' );
    $cat_ids   = array_filter( array_map( 'intval', explode( ',', $cats_raw  ) ) );
    $prod_ids  = array_filter( array_map( 'intval', explode( ',', $prods_raw ) ) );

    $data = [
        'enabled'          => isset($_POST['free_enabled']),
        'buy_quantity'     => 1, // Free rule locked to Buy 1
        'get_quantity'     => 1, // Free rule locked to Get 1
        'discount_type'    => sanitize_text_field($_POST['discount_type'] ?? 'percentage'),
        'discount_value'   => floatval($_POST['discount_value']    ?? 100),
        'apply_to'         => sanitize_text_field($_POST['apply_to']      ?? 'cheapest'),
        'min_cart_total'   => floatval($_POST['min_cart_total']    ?? 0),
        'max_uses_per_cart'=> intval($_POST['max_uses_per_cart']   ?? 1),
        'title'            => sanitize_text_field($_POST['rule_title']     ?? 'Buy One Get One'),
        'description'      => sanitize_textarea_field($_POST['rule_desc'] ?? ''),
        'exclude_sale'     => isset($_POST['exclude_sale']),
        'show_badge'       => isset($_POST['show_badge']),
        'badge_text'       => sanitize_text_field($_POST['badge_text']    ?? 'Deal'),
        'notify_cart'      => isset($_POST['notify_cart']),
        'cart_message'     => sanitize_text_field($_POST['cart_message']  ?? ''),
        'categories'       => $cat_ids,
        'products'         => $prod_ids,
        'priority'         => max(1, intval($_POST['rule_priority'] ?? 50)),
        'start_date'       => sanitize_text_field($_POST['rule_start_date'] ?? ''),
        'end_date'         => sanitize_text_field($_POST['rule_end_date']   ?? ''),
        'updated'          => current_time('mysql'),
    ];
    update_option('gtbogo_free_rule', $data);

    // Sync to wpqx_gtbogo_rules table so Cart_Enhanced can apply it
    if ( !empty($data['enabled']) ) {
        $existing = $wpdb->get_var("SELECT id FROM {$wpdb->prefix}gtbogo_rules WHERE pack_source='free_rule' LIMIT 1");
        $rule_data = [
            'name'           => sanitize_text_field($data['title'] ?? 'Free Rule'),
            'type'           => 'bogo',
            'buy_quantity'   => (int)($data['buy_quantity'] ?? 1),
            'get_quantity'   => (int)($data['get_quantity'] ?? 1),
            'discount_type'  => sanitize_text_field($data['discount_type'] ?? 'percentage'),
            'discount_value' => (float)($data['discount_value'] ?? 50),
            'min_cart_total' => (float)($data['min_cart_total'] ?? 0),
            'status'         => 'active',
            'priority'       => (int)($data['priority'] ?? 50),
            'pack_source'    => 'free_rule',
            'updated_at'     => current_time('mysql'),
        ];
        if ( $existing ) {
            $wpdb->update("{$wpdb->prefix}gtbogo_rules", $rule_data, ['id' => $existing]);
        } else {
            $rule_data['created_at'] = current_time('mysql');
            $wpdb->insert("{$wpdb->prefix}gtbogo_rules", $rule_data);
        }
    } else {
        // Disabled — deactivate in rules table
        $wpdb->update("{$wpdb->prefix}gtbogo_rules", ['status' => 'inactive'], ['pack_source' => 'free_rule']);
    }
    delete_transient('gtbogo_active_rules');
    delete_transient('gtbogo_active_rules_summary');

    // ── Sync individual options that the engine reads ──────────────────────
    update_option( 'gt_bogo_free_rule_enabled',        $data['enabled'] ? 1 : 0 );
    update_option( 'gt_bogo_free_rule_buy_qty',         $data['buy_quantity'] );
    update_option( 'gt_bogo_free_rule_get_qty',         $data['get_quantity'] );
    update_option( 'gt_bogo_free_rule_discount_type',   $data['discount_type'] );
    update_option( 'gt_bogo_free_rule_discount_value',  $data['discount_value'] );
    update_option( 'gt_bogo_free_rule_apply_to',        $data['apply_to'] );
    update_option( 'gt_bogo_free_rule_min_cart_total',  $data['min_cart_total'] );
    update_option( 'gt_bogo_free_rule_max_uses',        $data['max_uses_per_cart'] );
    update_option( 'gt_bogo_free_rule_title',           $data['title'] );
    update_option( 'gt_bogo_free_rule_exclude_sale',    $data['exclude_sale'] ? 1 : 0 );
    update_option( 'gt_bogo_free_rule_categories',      $data['categories'] ?? [] );
    update_option( 'gt_bogo_free_rule_products',        $data['products'] ?? [] );
    // ───────────────────────────────────────────────────────────────────────

    if (function_exists('gt_bogo_log')) gt_bogo_log('Free rule updated', ($data['enabled']?'Enabled':'Disabled').
        ' — Buy '.$data['buy_quantity'].' Get '.$data['get_quantity'].' '.$data['discount_value'].'%', 'success');
    delete_transient('gtbogo_active_rules');
    $message = 'Free rule saved.'; $message_type = 'success';
}

$r = get_option('gtbogo_free_rule', [
    'enabled'=>false,'buy_quantity'=>1,'get_quantity'=>1,'discount_type'=>'percentage',
    'discount_value'=>100,'apply_to'=>'cheapest','min_cart_total'=>0,'max_uses_per_cart'=>1,
    'title'=>'Buy One Get One','description'=>'','exclude_sale'=>false,'show_badge'=>false,
    'badge_text'=>'Deal','notify_cart'=>true,'cart_message'=>'Add another item to claim your free product.',
    'categories'=>[],'products'=>[],'priority'=>50,'start_date'=>'','end_date'=>'',
]);

// Stats from analytics
global $wpdb;
$atbl  = $wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $wpdb->prefix.'gtbogo_analytics'));
$stats = null;
if ($atbl) {
    $stats = $wpdb->get_row($wpdb->prepare(
        "SELECT COUNT(DISTINCT order_id) AS orders, COALESCE(SUM(order_total),0) AS revenue,
                COALESCE(SUM(discount_amount),0) AS discounts, COALESCE(AVG(order_total),0) AS aov
         FROM {$wpdb->prefix}gtbogo_analytics a LEFT JOIN {$wpdb->prefix}gtbogo_rules r ON a.rule_id=r.id WHERE a.date_created>=%s AND r.name=%s",
        gmdate('Y-m-d H:i:s', strtotime('-30 days')), $r['title']
    ), ARRAY_A);
}

require_once __DIR__ . '/../ui-system/wrapper-start.php';
?>
<div class="gt-page-header gt-animate-in">
    <div>
        <h1 class="gt-page-title">🎁 Free Core Rule</h1>
        <p class="gt-page-subtitle">Your always-available BOGO rule — no PRO license required. Full configuration, cart messaging, and badge control.</p>
    </div>
    <div style="display:flex;gap:8px;align-items:center">
        <span class="gt-badge <?php echo !empty($r['enabled'])?'gt-badge-active':'gt-badge-free'; ?>">
            <?php echo !empty($r['enabled'])?'● Rule Active':'○ Rule Inactive'; ?>
        </span>
        <span class="gt-badge gt-badge-free">Free — v<?php echo esc_html($version); ?></span>
    </div>
</div>
<?php if ($message): ?><div class="gt-notice gt-notice-<?php echo esc_attr($message_type); ?> gt-animate-in">✓ <?php echo esc_html($message); ?></div><?php endif; ?>

<!-- METRICS -->
<div class="gt-metrics gt-animate-in" style="margin-bottom:20px">
    <div class="gt-metric" style="--gt-metric-c:#e10000">
        <span class="gt-metric-icon">🎁</span>
        <div class="gt-metric-label">Rule Status</div>
        <div class="gt-metric-value" style="font-size:16px"><?php echo !empty($r['enabled'])?'Active':'Inactive'; ?></div>
        <div class="gt-metric-trend">Buy <?php echo esc_html( $r['buy_quantity'] ); ?> Get <?php echo esc_html( $r['get_quantity'] ); ?> — <?php echo esc_html( $r['discount_value'] ); ?>% off</div>
    </div>
    <div class="gt-metric" style="--gt-metric-c:#22c55e">
        <span class="gt-metric-icon">🛒</span>
        <div class="gt-metric-label">Orders (30d)</div>
        <div class="gt-metric-value"><?php echo esc_html( number_format($stats['orders']??0) ); ?></div>
        <div class="gt-metric-trend">BOGO orders this month</div>
    </div>
    <div class="gt-metric" style="--gt-metric-c:#3b82f6">
        <span class="gt-metric-icon">💰</span>
        <div class="gt-metric-label">Revenue (30d)</div>
        <div class="gt-metric-value" style="font-size:18px">$<?php echo esc_html( number_format($stats['revenue']??0,0) ); ?></div>
        <div class="gt-metric-trend">Influenced by this rule</div>
    </div>
    <div class="gt-metric" style="--gt-metric-c:#f59e0b">
        <span class="gt-metric-icon">🏷️</span>
        <div class="gt-metric-label">Discounts (30d)</div>
        <div class="gt-metric-value" style="font-size:18px">$<?php echo esc_html( number_format($stats['discounts']??0,0) ); ?></div>
        <div class="gt-metric-trend">Total discount given</div>
    </div>
    <div class="gt-metric" style="--gt-metric-c:#8b5cf6">
        <span class="gt-metric-icon">💵</span>
        <div class="gt-metric-label">Avg Order Value (30d)</div>
        <div class="gt-metric-value" style="font-size:18px">$<?php echo esc_html( number_format($stats['aov']??0,2) ); ?></div>
        <div class="gt-metric-trend">BOGO-influenced orders</div>
    </div>
</div>

<form method="post" action="">
<?php wp_nonce_field('gtbogo_free_rule'); ?>

<!-- RULE STATUS + IDENTITY -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
    <div class="gt-card-header"><h2 class="gt-card-title">⚙️ Rule Configuration</h2></div>

    <div class="gt-setting-row">
        <div>
            <div class="gt-setting-label" style="font-size:16px">Enable Free Core Rule</div>
            <div class="gt-setting-desc">When enabled, this BOGO rule is active on your store immediately. No PRO license required.</div>
        </div>
        <label class="gt-toggle"><input type="checkbox" name="free_enabled" value="1" <?php checked(!empty($r['enabled'])); ?>><span class="gt-toggle-track"><span class="gt-toggle-thumb"></span></span></label>
    </div>

    <div style="display:grid;grid-template-columns:1fr 1fr;gap:20px;margin-top:4px">
        <div class="gt-form-group">
            <label class="gt-form-label">Rule Display Name</label>
            <input type="text" name="rule_title" class="gt-input" value="<?php echo esc_attr($r['title']); ?>" placeholder="Buy One Get One">
            <div class="gt-form-hint">Shown in cart messages, deal page, and analytics</div>
        </div>
        <div class="gt-form-group">
            <label class="gt-form-label">Rule Description (optional)</label>
            <input type="text" name="rule_desc" class="gt-input" value="<?php echo esc_attr($r['description']); ?>" placeholder="Add two items to claim a complimentary product">
            <div class="gt-form-hint">Used on the deal page if enabled</div>
        </div>
    </div>
</div>

<!-- DEAL STRUCTURE -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
    <div class="gt-card-header"><h2 class="gt-card-title">🎯 Deal Structure</h2></div>

    <div style="display:grid;grid-template-columns:repeat(4,1fr);gap:16px;margin-bottom:20px">
        <div class="gt-form-group" style="margin:0">
            <label class="gt-form-label">Buy Quantity</label>
            <input type="number" name="buy_qty" class="gt-input" value="1" min="1" max="1" readonly style="cursor:not-allowed">
            <div class="gt-form-hint">Items customer must add</div>
        </div>
        <div class="gt-form-group" style="margin:0">
            <label class="gt-form-label">Get Quantity</label>
            <input type="number" name="get_qty" class="gt-input" value="1" min="1" max="1" readonly style="cursor:not-allowed">
            <div class="gt-form-hint">Items discounted or free</div>
        </div>
        <div class="gt-form-group" style="margin:0">
            <label class="gt-form-label">Discount Type</label>
            <select name="discount_type" class="gt-select">
                <option value="percentage" <?php selected($r['discount_type'],'percentage'); ?>>Percentage Off</option>
                <option value="fixed"      <?php selected($r['discount_type'],'fixed'); ?>>Fixed Amount Off</option>
            </select>
        </div>
        <div class="gt-form-group" style="margin:0">
            <label class="gt-form-label">Discount Value</label>
            <input type="number" name="discount_value" class="gt-input" value="<?php echo esc_attr($r['discount_value']); ?>" min="1" max="100" step="0.01">
            <div class="gt-form-hint">100 = fully free</div>
        </div>
    </div>

    <div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:16px">
        <div class="gt-form-group">
            <label class="gt-form-label">Apply Discount To</label>
            <select name="apply_to" class="gt-select" onchange="frApplyToChange(this)">
                <option value="cheapest"   <?php selected($r['apply_to'],'cheapest'); ?>>Cheapest item in cart (protects your margin)</option>
                <option value="cheapest_n" <?php selected($r['apply_to'],'cheapest_n'); ?>>Multiple cheapest items (set how many)</option>
                <option value="most_exp"   <?php selected($r['apply_to'],'most_exp'); ?>>Most expensive item in cart</option>
                <?php if($_gt_is_pro): ?><option value="specific" <?php selected($r['apply_to'],'specific'); ?>>Specific product only</option><?php else: ?><option value="specific" disabled style="color:#475569">Specific product only (PRO)</option><?php endif; ?>
            </select>
            <div class="gt-form-hint">Which cart item receives the discount</div>
        </div>
        <div class="gt-form-group">
            <label class="gt-form-label">Minimum Cart Total ($)</label>
            <input type="number" name="min_cart_total" class="gt-input" value="<?php echo esc_attr($r['min_cart_total']); ?>" min="0" step="0.01" placeholder="0.00">
            <div class="gt-form-hint">Cart subtotal before this rule fires. 0 = no minimum.</div>
        </div>
        <div class="gt-form-group">
            <label class="gt-form-label">Max Uses Per Cart</label>
            <input type="number" name="max_uses_per_cart" class="gt-input" value="<?php echo esc_attr($r['max_uses_per_cart']); ?>" min="1" max="99">
            <div class="gt-form-hint">How many times the deal can stack in a single order</div>
        </div>
    </div>

    <div class="gt-setting-row" style="border:none;padding-top:4px">
        <div><div class="gt-setting-label">Exclude Sale-Priced Items</div><div class="gt-setting-desc">Do not apply the BOGO discount to items already on sale. Prevents double-discounting and protects margin.</div></div>
        <label class="gt-toggle"><input type="checkbox" name="exclude_sale" value="1" <?php checked(!empty($r['exclude_sale'])); ?>><span class="gt-toggle-track"><span class="gt-toggle-thumb"></span></span></label>
    </div>
</div>

<!-- DEAL STRUCTURE PREVIEW -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
    <div class="gt-card-header"><h2 class="gt-card-title">👁 Deal Preview</h2><span class="gt-text-soft" style="font-size:13px">Updates as you type</span></div>
    <div id="deal-preview" style="padding:20px;background:rgba(225,0,0,0.04);border-radius:10px;border:1px solid rgba(225,0,0,0.15);text-align:center">
        <div id="preview-headline" style="font-size:22px;font-weight:800;color:var(--gt-white);margin-bottom:8px">Buy 1 Get 1 — 100% Off</div>
        <div id="preview-sub" style="font-size:13px;color:var(--gt-soft)">Cheapest eligible item receives the discount. Minimum cart: none.</div>
    </div>
    <script>
    function updatePreview() {
        var buy  = document.querySelector('[name=buy_qty]').value;
        var get  = document.querySelector('[name=get_qty]').value;
        var val  = document.querySelector('[name=discount_value]').value;
        var type = document.querySelector('[name=discount_type]').value;
        var to   = document.querySelector('[name=apply_to]').value;
        var min  = document.querySelector('[name=min_cart_total]').value;
        var suffix = type==='percentage' ? '%' : ' off';
        var toLabel = {cheapest:'Cheapest item',cheapest_n:'N cheapest items',most_exp:'Most expensive item',specific:'Specific product'}[to]||to;
        document.getElementById('preview-headline').textContent = 'Buy ' + buy + ' Get ' + get + ' — ' + val + suffix;
        document.getElementById('preview-sub').textContent = toLabel + ' receives the discount.' + (min>0?' Minimum cart: $'+parseFloat(min).toFixed(2)+'.':' No minimum cart required.');
    }
    document.querySelectorAll('[name=buy_qty],[name=get_qty],[name=discount_value],[name=discount_type],[name=apply_to],[name=min_cart_total]').forEach(el=>el.addEventListener('input',updatePreview));

function frApplyToChange(sel) {
    if (sel.value === 'specific') {
        sel.value = '<?php echo esc_js($r["apply_to"]); ?>';
        var banner = document.getElementById('fr-pro-apply-banner');
        if (!banner) {
            banner = document.createElement('div');
            banner.id = 'fr-pro-apply-banner';
            banner.style.cssText = 'margin-top:8px;padding:10px 14px;background:rgba(225,0,0,0.08);border:1px solid rgba(225,0,0,0.2);border-radius:8px;font-size:12px;color:#fff';
            banner.innerHTML = 'Targeting specific products requires PRO. <a href="<?php echo esc_url( admin_url("admin.php?page=gt-bogo-engine&tab=license") ); ?>" style="color:#E10000;font-weight:700">Activate PRO</a> to unlock product-level targeting, custom quantities, role gating, scheduling, and 200 rule templates.';
            sel.parentNode.appendChild(banner);
        }
        banner.style.display = 'block';
    } else {
        var banner = document.getElementById('fr-pro-apply-banner');
        if (banner) banner.style.display = 'none';
    }
    updatePreview();
}
    document.querySelectorAll('[name=discount_type],[name=apply_to]').forEach(el=>el.addEventListener('change',updatePreview));
    updatePreview();
    </script>
</div>

<!-- TARGETING & SCHEDULING -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
    <div class="gt-card-header"><h2 class="gt-card-title">🎯 Targeting</h2></div>

    <style>
    .gt-target-section{background:rgba(255,255,255,0.02);border:1px solid var(--gt-border);border-radius:10px;overflow:hidden;margin-bottom:12px}
    .gt-target-header{display:flex;align-items:center;justify-content:space-between;padding:10px 14px;cursor:pointer;user-select:none;border-bottom:1px solid transparent}
    .gt-target-header.open{border-bottom-color:var(--gt-border)}
    .gt-target-header-left{display:flex;align-items:center;gap:8px}
    .gt-target-header-title{font-size:13px;font-weight:700;color:#fff}
    .gt-target-header-badge{font-size:11px;background:rgba(225,0,0,0.12);border:1px solid rgba(225,0,0,0.2);color:#E10000;border-radius:999px;padding:1px 8px;display:none}
    .gt-target-header-badge.active{display:inline-block}
    .gt-target-body{padding:14px;display:none}
    .gt-target-body.open{display:block}
    .gt-target-chevron{color:#475569;font-size:10px;transition:transform .15s}
    .gt-target-header.open .gt-target-chevron{transform:rotate(180deg)}
    /* Product search */
    .gt-prod-search-wrap{position:relative;margin-bottom:10px}
    .gt-prod-search-input{width:100%;padding:8px 12px 8px 34px;background:rgba(255,255,255,0.04);border:1px solid var(--gt-border);border-radius:8px;color:#fff;font-size:13px;box-sizing:border-box;outline:none}
    .gt-prod-search-input:focus{border-color:rgba(225,0,0,0.4)}
    .gt-prod-search-icon{position:absolute;left:12px;top:50%;transform:translateY(-50%);color:#475569;font-size:14px;pointer-events:none;z-index:1}
    .gt-prod-results{max-height:220px;overflow-y:auto;border:1px solid var(--gt-border);border-radius:8px;background:#0a1628;display:none}
    .gt-prod-results.open{display:block}
    .gt-prod-result-item{display:flex;align-items:center;gap:10px;padding:8px 12px;cursor:pointer;border-bottom:1px solid rgba(255,255,255,0.04)}
    .gt-prod-result-item:last-child{border-bottom:none}
    .gt-prod-result-item:hover{background:rgba(255,255,255,0.04)}
    .gt-prod-result-item.selected{background:rgba(225,0,0,0.06)}
    .gt-prod-result-img{width:32px;height:32px;border-radius:4px;object-fit:cover;flex-shrink:0;background:#0f1a30}
    .gt-prod-result-name{font-size:12px;font-weight:600;color:#fff;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
    .gt-prod-result-meta{font-size:11px;color:#475569;margin-top:1px}
    .gt-prod-result-check{width:16px;height:16px;border-radius:3px;border:1.5px solid #475569;flex-shrink:0;display:flex;align-items:center;justify-content:center;margin-left:auto}
    .gt-prod-result-check.on{background:#E10000;border-color:#E10000}
    /* Selected tags */
    .gt-selected-tags{display:flex;flex-wrap:wrap;gap:6px;margin-bottom:10px;min-height:0}
    .gt-sel-tag{display:flex;align-items:center;gap:5px;background:rgba(225,0,0,0.1);border:1px solid rgba(225,0,0,0.2);border-radius:6px;padding:3px 8px;font-size:12px;color:#fff}
    .gt-sel-tag.blue{background:rgba(59,130,246,0.1);border-color:rgba(59,130,246,0.2)}
    .gt-sel-tag.green{background:rgba(34,197,94,0.1);border-color:rgba(34,197,94,0.2)}
    .gt-sel-tag-remove{background:none;border:none;color:#94a3b8;cursor:pointer;padding:0;font-size:13px;line-height:1;display:flex;align-items:center}
    .gt-sel-tag-remove:hover{color:#ef4444}
    /* Category checkboxes */
    .gt-cat-list{display:grid;grid-template-columns:repeat(auto-fill,minmax(180px,1fr));gap:6px;max-height:200px;overflow-y:auto}
    .gt-cat-item{display:flex;align-items:center;gap:8px;padding:6px 10px;border-radius:6px;cursor:pointer;border:1px solid transparent}
    .gt-cat-item:hover{background:rgba(255,255,255,0.03);border-color:var(--gt-border)} .gt-cat-item input[type=checkbox]{appearance:none;-webkit-appearance:none;background:#0a1628}
    .gt-cat-item.selected{background:rgba(59,130,246,0.08);border-color:rgba(59,130,246,0.2)}
    .gt-cat-cb{width:16px;height:16px;border-radius:3px;border:1.5px solid #475569;flex-shrink:0;display:flex;align-items:center;justify-content:center;background:#0a1628}
    .gt-cat-cb.on{background:#3b82f6;border-color:#3b82f6}
    .gt-cat-name{font-size:12px;color:#cbd5e1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
    .gt-cat-count{font-size:10px;color:#475569;margin-left:auto;flex-shrink:0}
    /* Toggle buttons */
    .gt-toggle-group{display:flex;gap:6px;flex-wrap:wrap}
    .gt-tog-btn{padding:5px 12px;border-radius:6px;border:1px solid var(--gt-border);background:rgba(255,255,255,0.03);color:#94a3b8;font-size:12px;cursor:pointer;transition:all .15s}
    .gt-tog-btn.on{background:rgba(225,0,0,0.1);border-color:rgba(225,0,0,0.3);color:#fff;font-weight:600}
    .gt-tog-btn.on.blue{background:rgba(59,130,246,0.1);border-color:rgba(59,130,246,0.3)}
    .gt-tog-btn.on.green{background:rgba(34,197,94,0.1);border-color:rgba(34,197,94,0.3)}
    /* Pagination */
    .gt-prod-pagination{display:flex;align-items:center;gap:8px;margin-top:8px;font-size:12px;color:#475569}
    .gt-prod-pag-btn{padding:4px 10px;background:rgba(255,255,255,0.04);border:1px solid var(--gt-border);border-radius:5px;color:#94a3b8;cursor:pointer;font-size:11px}
    .gt-prod-pag-btn:disabled{opacity:0.35;cursor:default}
    </style>

    <?php
    // Load saved data
    $saved_prod_ids = array_filter(array_map('intval', $r['products'] ?? []));
    $saved_cat_ids  = array_filter(array_map('intval', $r['categories'] ?? []));
    $saved_tags     = array_filter(array_map('intval', $r['tags'] ?? []));
    $saved_type     = sanitize_text_field($r['product_type'] ?? '');
    $saved_stock    = sanitize_text_field($r['stock_status'] ?? '');
    $saved_on_sale  = isset($r['on_sale']) ? (int)$r['on_sale'] : -1;

    // Load all categories
    $all_cats = get_terms(['taxonomy'=>'product_cat','hide_empty'=>false,'number'=>500,'orderby'=>'name']);
    // Load all tags
    $all_tags = get_terms(['taxonomy'=>'product_tag','hide_empty'=>true,'number'=>200,'orderby'=>'count','order'=>'DESC']);
    // Load saved product names
    $saved_products = [];
    foreach($saved_prod_ids as $pid) {
        $p = wc_get_product($pid);
        if($p) $saved_products[] = ['id'=>$pid,'name'=>$p->get_name()];
    }
    // Load saved tag names
    $saved_tag_names = [];
    foreach($saved_tags as $tid) {
        $t = get_term($tid, 'product_tag');
        if($t && !is_wp_error($t)) $saved_tag_names[] = ['id'=>$tid,'name'=>$t->name];
    }
    ?>

    <input type="hidden" name="rule_products"     id="fr-products-val"  value="<?php echo esc_attr(implode(',', $saved_prod_ids)); ?>">
    <input type="hidden" name="rule_categories"   id="fr-cats-val"      value="<?php echo esc_attr(implode(',', $saved_cat_ids)); ?>">
    <input type="hidden" name="rule_tags"         id="fr-tags-val"      value="<?php echo esc_attr(implode(',', $saved_tags)); ?>">
    <input type="hidden" name="rule_product_type" id="fr-type-val"      value="<?php echo esc_attr($saved_type); ?>">
    <input type="hidden" name="rule_stock_status" id="fr-stock-val"     value="<?php echo esc_attr($saved_stock); ?>">
    <input type="hidden" name="rule_on_sale"      id="fr-sale-val"      value="<?php echo esc_attr($saved_on_sale); ?>">

    <!-- PRODUCTS -->
    <div class="gt-target-section">
        <div class="gt-target-header open" onclick="gtTargetToggle(this)">
            <div class="gt-target-header-left">
                <span style="font-size:16px">📦</span>
                <span class="gt-target-header-title">Specific Products</span>
                <span class="gt-target-header-badge <?php echo !empty($saved_products)?'active':''; ?>" id="fr-prod-badge"><?php echo count($saved_products); ?> selected</span>
            </div>
            <div style="display:flex;align-items:center;gap:8px">
                <span style="font-size:11px;color:#475569">Leave empty = all products</span>
                <span class="gt-target-chevron">▲</span>
            </div>
        </div>
        <div class="gt-target-body open">
            <!-- Selected tags -->
            <div class="gt-selected-tags" id="fr-prod-tags">
                <?php foreach($saved_products as $sp): ?>
                <span class="gt-sel-tag" data-id="<?php echo esc_html( $sp['id'] ); ?>">
                    <?php echo esc_html($sp['name']); ?>
                    <button type="button" class="gt-sel-tag-remove" onclick="frRemoveProduct(<?php echo esc_html( $sp['id'] ); ?>,this.parentNode)">×</button>
                </span>
                <?php endforeach; ?>
            </div>
            <!-- Search -->
            <div class="gt-prod-search-wrap">
                <span class="gt-prod-search-icon">🔍</span>
                <input type="text" class="gt-prod-search-input" id="fr-prod-search" style="padding-left:36px!important"
                    placeholder="Search products by name or SKU..."
                    oninput="frProductSearch(this.value)" autocomplete="off">
            </div>
            <!-- Filters row -->
            <div style="display:flex;gap:8px;margin-bottom:8px;flex-wrap:wrap">
                <select id="fr-prod-cat-filter" onchange="frProductSearch(document.getElementById('fr-prod-search').value)"
                    style="padding:5px 10px;background:#0a1628;border:1px solid var(--gt-border);border-radius:6px;color:#e2e8f0;font-size:12px;color-scheme:dark;accent-color:#3b82f6">
                    <option value="">All Categories</option>
                    <?php foreach((array)$all_cats as $cat): if(is_wp_error($cat)) continue; ?>
                    <option value="<?php echo esc_attr( $cat->term_id ); ?>"><?php echo esc_html($cat->name); ?> (<?php echo esc_html( $cat->count ); ?>)</option>
                    <?php endforeach; ?>
                </select>
                <select id="fr-prod-type-filter" onchange="frProductSearch(document.getElementById('fr-prod-search').value)"
                    style="padding:5px 10px;background:#0a1628;border:1px solid var(--gt-border);border-radius:6px;color:#e2e8f0;font-size:12px;color-scheme:dark;accent-color:#3b82f6">
                    <option value="">All Types</option>
                    <option value="simple">Simple</option>
                    <option value="variable">Variable</option>
                    <option value="grouped">Grouped</option>
                    <option value="external">External</option>
                </select>
                <select id="fr-prod-stock-filter" onchange="frProductSearch(document.getElementById('fr-prod-search').value)"
                    style="padding:5px 10px;background:#0a1628;border:1px solid var(--gt-border);border-radius:6px;color:#e2e8f0;font-size:12px;color-scheme:dark;accent-color:#3b82f6">
                    <option value="">Any Stock Status</option>
                    <option value="instock">In Stock</option>
                    <option value="outofstock">Out of Stock</option>
                    <option value="onbackorder">On Backorder</option>
                </select>
                <select id="fr-prod-sale-filter" onchange="frProductSearch(document.getElementById('fr-prod-search').value)"
                    style="padding:5px 10px;background:#0a1628;border:1px solid var(--gt-border);border-radius:6px;color:#e2e8f0;font-size:12px;color-scheme:dark;accent-color:#3b82f6">
                    <option value="">Sale Status: Any</option>
                    <option value="1">On Sale Only</option>
                    <option value="0">Not On Sale</option>
                </select>
                <select id="fr-prod-orderby" onchange="frProductSearch(document.getElementById('fr-prod-search').value)"
                    style="padding:5px 10px;background:#0a1628;border:1px solid var(--gt-border);border-radius:6px;color:#e2e8f0;font-size:12px;color-scheme:dark;accent-color:#3b82f6">
                    <option value="title">Sort: A-Z</option>
                    <option value="date">Sort: Newest</option>
                    <option value="price">Sort: Price Low</option>
                    <option value="price-desc">Sort: Price High</option>
                    <option value="popularity">Sort: Popular</option>
                </select>
                <select id="fr-prod-perpage" onchange="frProductSearch(document.getElementById('fr-prod-search').value)"
                    style="padding:5px 10px;background:#0a1628;border:1px solid var(--gt-border);border-radius:6px;color:#e2e8f0;font-size:12px;color-scheme:dark;accent-color:#3b82f6">
                    <option value="20" selected>20 / page</option>
                    <option value="50">50 / page</option>
                    <option value="100">100 / page</option>
                    <option value="500">500 / page</option>
                    <option value="1000">1000 / page</option>
                </select>
                <span style="margin-left:auto;font-size:11px;color:#475569;align-self:center" id="fr-prod-count-label"></span>
            </div>
            <!-- Results -->
            <div class="gt-prod-results" id="fr-prod-results"></div>
            <!-- Pagination -->
            <div class="gt-prod-pagination" id="fr-prod-pag" style="display:none">
                <button class="gt-prod-pag-btn" id="fr-prod-prev" onclick="frProductPage(-1)" disabled>← Prev</button>
                <span id="fr-prod-pag-info">Page 1</span>
                <button class="gt-prod-pag-btn" id="fr-prod-next" onclick="frProductPage(1)">Next →</button>
            </div>
        </div>
    </div>

    <!-- CATEGORIES -->
    <div class="gt-target-section">
        <div class="gt-target-header open" onclick="gtTargetToggle(this)">
            <div class="gt-target-header-left">
                <span style="font-size:16px">🗂️</span>
                <span class="gt-target-header-title">Categories</span>
                <span class="gt-target-header-badge <?php echo !empty($saved_cat_ids)?'active':''; ?>" id="fr-cat-badge"><?php echo count($saved_cat_ids); ?> selected</span>
            </div>
            <div style="display:flex;align-items:center;gap:8px">
                <span style="font-size:11px;color:#475569">Leave empty = all categories</span>
                <span class="gt-target-chevron">▲</span>
            </div>
        </div>
        <div class="gt-target-body open">
            <div style="margin-bottom:8px">
                <input type="text" placeholder="Filter categories..." oninput="frFilterCats(this.value)"
                    style="width:100%;padding:7px 12px;background:#0a1628;border:1px solid var(--gt-border);border-radius:7px;color:#fff;font-size:13px;box-sizing:border-box;outline:none">
            </div>
            <div class="gt-cat-list" id="fr-cat-list">
                <?php foreach((array)$all_cats as $cat): if(is_wp_error($cat)) continue;
                    $sel = in_array($cat->term_id, $saved_cat_ids); ?>
                <div class="gt-cat-item <?php echo esc_html( $sel )?'selected':''; ?>"
                    data-id="<?php echo esc_attr( $cat->term_id ); ?>"
                    data-name="<?php echo esc_attr($cat->name); ?>"
                    onclick="frToggleCat(<?php echo esc_js( $cat->term_id ); ?>,<?php echo esc_js(json_encode($cat->name)); ?>,this)">
                    <div class="gt-cat-cb <?php echo esc_html( $sel )?'on':''; ?>">
                        <?php if($sel): ?><span style="color:#fff;font-size:9px;font-weight:800">✓</span><?php endif; ?>
                    </div>
                    <span class="gt-cat-name"><?php echo esc_html($cat->name); ?></span>
                    <span class="gt-cat-count"><?php echo esc_html( $cat->count ); ?></span>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
    </div>

    <!-- TAGS -->
    <?php if(!empty($all_tags) && !is_wp_error($all_tags)): ?>
    <div class="gt-target-section">
        <div class="gt-target-header" onclick="gtTargetToggle(this)">
            <div class="gt-target-header-left">
                <span style="font-size:16px">🏷️</span>
                <span class="gt-target-header-title">Product Tags</span>
                <span class="gt-target-header-badge <?php echo !empty($saved_tags)?'active':''; ?>" id="fr-tag-badge"><?php echo count($saved_tags); ?> selected</span>
            </div>
            <div style="display:flex;align-items:center;gap:8px">
                <span style="font-size:11px;color:#475569">Target by tag</span>
                <span class="gt-target-chevron">▼</span>
            </div>
        </div>
        <div class="gt-target-body">
            <div style="margin-bottom:8px">
                <input type="text" placeholder="Filter tags..." oninput="frFilterTags(this.value)"
                    style="width:100%;padding:7px 12px;background:#0a1628;border:1px solid var(--gt-border);border-radius:7px;color:#fff;font-size:13px;box-sizing:border-box;outline:none">
            </div>
            <div class="gt-cat-list" id="fr-tag-list">
                <?php foreach((array)$all_tags as $tag): if(is_wp_error($tag)) continue;
                    $sel = in_array($tag->term_id, $saved_tags); ?>
                <div class="gt-cat-item <?php echo esc_html( $sel )?'selected':''; ?> green"
                    data-id="<?php echo esc_attr( $tag->term_id ); ?>"
                    data-name="<?php echo esc_attr($tag->name); ?>"
                    onclick="frToggleTag(<?php echo esc_js( $tag->term_id ); ?>,<?php echo esc_js(json_encode($tag->name)); ?>,this)">
                    <div class="gt-cat-cb <?php echo esc_html( $sel )?'on':''; ?>" style="<?php echo esc_html( $sel )?'background:#22c55e;border-color:#22c55e':''; ?>">
                        <?php if($sel): ?><span style="color:#fff;font-size:9px;font-weight:800">✓</span><?php endif; ?>
                    </div>
                    <span class="gt-cat-name"><?php echo esc_html($tag->name); ?></span>
                    <span class="gt-cat-count"><?php echo esc_html( $tag->count ); ?></span>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
    </div>
    <?php endif; ?>

    <!-- PRODUCT TYPE + STOCK + SALE -->
    <div class="gt-target-section">
        <div class="gt-target-header" onclick="gtTargetToggle(this)">
            <div class="gt-target-header-left">
                <span style="font-size:16px">⚙️</span>
                <span class="gt-target-header-title">Product Filters</span>
                <span class="gt-target-header-badge <?php echo ($saved_type||$saved_stock||$saved_on_sale>=0)?'active':''; ?>" id="fr-filter-badge">Active</span>
            </div>
            <span class="gt-target-chevron">▼</span>
        </div>
        <div class="gt-target-body">
            <div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:16px">
                <div>
                    <div style="font-size:12px;font-weight:700;color:#94a3b8;margin-bottom:8px;text-transform:uppercase;letter-spacing:.05em">Product Type</div>
                    <div class="gt-toggle-group" id="fr-type-group">
                        <?php foreach([''=>'Any','simple'=>'Simple','variable'=>'Variable','grouped'=>'Grouped','external'=>'External'] as $val=>$label): ?>
                        <button type="button" class="gt-tog-btn <?php echo $saved_type===$val?'on':''; ?>"
                            onclick="frSetType('<?php echo esc_html( $val ); ?>',this)"><?php echo esc_html( $label ); ?></button>
                        <?php endforeach; ?>
                    </div>
                </div>
                <div>
                    <div style="font-size:12px;font-weight:700;color:#94a3b8;margin-bottom:8px;text-transform:uppercase;letter-spacing:.05em">Stock Status</div>
                    <div class="gt-toggle-group" id="fr-stock-group">
                        <?php foreach([''=>'Any','instock'=>'In Stock','outofstock'=>'Out of Stock','onbackorder'=>'Backorder'] as $val=>$label): ?>
                        <button type="button" class="gt-tog-btn blue <?php echo $saved_stock===$val?'on':''; ?>"
                            onclick="frSetStock('<?php echo esc_html( $val ); ?>',this)"><?php echo esc_html( $label ); ?></button>
                        <?php endforeach; ?>
                    </div>
                </div>
                <div>
                    <div style="font-size:12px;font-weight:700;color:#94a3b8;margin-bottom:8px;text-transform:uppercase;letter-spacing:.05em">Sale Status</div>
                    <div class="gt-toggle-group" id="fr-sale-group">
                        <?php foreach(['-1'=>'Any','1'=>'On Sale','0'=>'Not On Sale'] as $val=>$label): ?>
                        <button type="button" class="gt-tog-btn green <?php echo (string)$saved_on_sale===$val?'on':''; ?>"
                            onclick="frSetSale('<?php echo esc_html( $val ); ?>',this)"><?php echo esc_html( $label ); ?></button>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- PRIORITY + DATES -->
    <div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:16px;margin-top:4px">
        <div class="gt-form-group" style="margin:0">
            <label class="gt-form-label">Priority</label>
            <input type="number" name="rule_priority" class="gt-input" value="<?php echo esc_attr($r['priority'] ?? 50); ?>" min="1" max="999">
            <div class="gt-form-hint">Lower number = higher priority. Default: 50.</div>
        </div>
        <div class="gt-form-group" style="margin:0">
            <label class="gt-form-label">Start Date <span style="color:var(--gt-subtle);font-weight:400">(optional)</span></label>
            <input type="datetime-local" name="rule_start_date" class="gt-input" value="<?php echo esc_attr($r['start_date'] ?? ''); ?>">
            <div class="gt-form-hint">Leave empty to run immediately</div>
        </div>
        <div class="gt-form-group" style="margin:0">
            <label class="gt-form-label">End Date <span style="color:var(--gt-subtle);font-weight:400">(optional)</span></label>
            <input type="datetime-local" name="rule_end_date" class="gt-input" value="<?php echo esc_attr($r['end_date'] ?? ''); ?>">
            <div class="gt-form-hint">Leave empty to run indefinitely</div>
        </div>
    </div>
</div>

<script>
var _frNonce  = '<?php echo esc_js(wp_create_nonce("gtbogo_product_search")); ?>';
var _frAjax   = '<?php echo esc_js(admin_url("admin-ajax.php")); ?>';

// ── Targeting state ────────────────────────────────────────────────────────
var frProdState = {page:1, pages:1, total:0, search:'', cat:'', type:'', stock:'', sale:'', timer:null};

// ── Section accordion ──────────────────────────────────────────────────────
function gtTargetToggle(header) {
    var body = header.nextElementSibling;
    var open = body.classList.contains('open');
    body.classList.toggle('open', !open);
    header.classList.toggle('open', !open);
}

// ── Product search ─────────────────────────────────────────────────────────
function frProductSearch(val) {
    frProdState.search = val;
    frProdState.page   = 1;
    frProdState.cat    = document.getElementById('fr-prod-cat-filter').value;
    frProdState.type   = document.getElementById('fr-prod-type-filter').value;
    frProdState.stock  = document.getElementById('fr-prod-stock-filter').value;
    frProdState.sale   = document.getElementById('fr-prod-sale-filter').value;
    clearTimeout(frProdState.timer);
    frProdState.timer = setTimeout(frProductLoad, 300);
}

function frProductPage(dir) {
    frProdState.page = Math.max(1, Math.min(frProdState.pages, frProdState.page + dir));
    frProductLoad();
}

function frProductLoad() {
    var results = document.getElementById('fr-prod-results');
    if(!frProdState.search && !frProdState.cat && !frProdState.type && !frProdState.stock && !frProdState.sale) {
        results.classList.remove('open');
        document.getElementById('fr-prod-pag').style.display = 'none';
        document.getElementById('fr-prod-count-label').textContent = '';
        return;
    }
    results.classList.add('open');
    results.innerHTML = '<div style="padding:16px;text-align:center;color:#475569;font-size:13px">Searching...</div>';
    var selectedIds = (document.getElementById('fr-products-val').value||'').split(',').filter(Boolean).map(Number);
    var fd = new FormData();
    fd.append('action','gtbogo_search_products');
    fd.append('nonce', _frNonce);
    fd.append('search', frProdState.search);
    fd.append('page', frProdState.page);
    fd.append('per_page', 20);
    fd.append('category_id', frProdState.cat);
    fd.append('stock_status', frProdState.stock);
    fd.append('product_type', frProdState.type);
    fd.append('on_sale', frProdState.sale);
    fd.append('orderby', document.getElementById('fr-prod-orderby') ? document.getElementById('fr-prod-orderby').value : 'title');
    fd.append('per_page', document.getElementById('fr-prod-perpage') ? document.getElementById('fr-prod-perpage').value : 20);
    fetch(_frAjax,{method:'POST',body:fd,credentials:'same-origin'})
    .then(function(r){return r.json();})
    .then(function(res){
        if(!res.success){results.innerHTML='<div style="padding:16px;color:#ef4444;font-size:13px">Error loading products.</div>';return;}
        var d=res.data;
        frProdState.pages=d.pages||1;
        frProdState.total=d.total||0;
        // Render results
        var html='';
        (d.products||[]).forEach(function(p){
            var sel = selectedIds.indexOf(p.id) > -1;
            html += '<div class="gt-prod-result-item'+(sel?' selected':'')+'" onclick="frToggleProduct('+JSON.stringify(p)+',this)" data-id="'+p.id+'">'
                + '<img class="gt-prod-result-img" src="'+(p.image||'')+'" onerror="this.src=\'data:image/svg+xml,<svg xmlns=&quot;http://www.w3.org/2000/svg&quot; width=&quot;32&quot; height=&quot;32&quot; fill=&quot;%230f1a30&quot;><rect width=&quot;32&quot; height=&quot;32&quot;/></svg>\'">'
                + '<div style="flex:1;min-width:0">'
                + '<div class="gt-prod-result-name">'+p.name+'</div>'
                + '<div class="gt-prod-result-meta">'+p.price+(p.sku?' · SKU: '+p.sku:'')+' · '+p.type+'</div>'
                + '</div>'
                + '<div class="gt-prod-result-check'+(sel?' on':'')">'+(sel?'<span style="color:#fff;font-size:9px;font-weight:800">✓</span>':'')+'</div>'
                + '</div>';
        });
        if(!html) html='<div style="padding:20px;text-align:center;color:#475569;font-size:13px">No products found.</div>';
        results.innerHTML=html;
        // Pagination
        var pag=document.getElementById('fr-prod-pag');
        if(frProdState.pages>1){
            pag.style.display='flex';
            document.getElementById('fr-prod-pag-info').textContent='Page '+frProdState.page+' of '+frProdState.pages+' ('+frProdState.total.toLocaleString()+' total)';
            document.getElementById('fr-prod-prev').disabled=frProdState.page<=1;
            document.getElementById('fr-prod-next').disabled=frProdState.page>=frProdState.pages;
        } else {
            pag.style.display='none';
        }
        document.getElementById('fr-prod-count-label').textContent=frProdState.total.toLocaleString()+' product'+(frProdState.total!==1?'s':'');
    });
}

function frToggleProduct(p, el) {
    var val   = document.getElementById('fr-products-val');
    var ids   = val.value ? val.value.split(',').filter(Boolean).map(Number) : [];
    var idx   = ids.indexOf(p.id);
    var tags  = document.getElementById('fr-prod-tags');
    if(idx > -1) {
        ids.splice(idx, 1);
        el.classList.remove('selected');
        el.querySelector('.gt-prod-result-check').classList.remove('on');
        el.querySelector('.gt-prod-result-check').innerHTML='';
        // Remove tag
        var tag = tags.querySelector('[data-id="'+p.id+'"]');
        if(tag) tag.remove();
    } else {
        ids.push(p.id);
        el.classList.add('selected');
        el.querySelector('.gt-prod-result-check').classList.add('on');
        el.querySelector('.gt-prod-result-check').innerHTML='<span style="color:#fff;font-size:9px;font-weight:800">✓</span>';
        // Add tag
        var tag=document.createElement('span');
        tag.className='gt-sel-tag';tag.dataset.id=p.id;
        tag.innerHTML=p.name+'<button type="button" class="gt-sel-tag-remove" onclick="frRemoveProduct('+p.id+',this.parentNode)">×</button>';
        tags.appendChild(tag);
    }
    val.value=ids.join(',');
    frUpdateBadge('fr-prod-badge', ids.length);
}

function frRemoveProduct(id, el) {
    var val = document.getElementById('fr-products-val');
    var ids = val.value ? val.value.split(',').filter(Boolean).map(Number) : [];
    ids = ids.filter(function(i){return i!==id;});
    val.value = ids.join(',');
    el.remove();
    // Uncheck in results if visible
    var ri = document.querySelector('#fr-prod-results [data-id="'+id+'"]');
    if(ri){ri.classList.remove('selected');ri.querySelector('.gt-prod-result-check').classList.remove('on');ri.querySelector('.gt-prod-result-check').innerHTML='';}
    frUpdateBadge('fr-prod-badge', ids.length);
}

// ── Categories ─────────────────────────────────────────────────────────────
function frToggleCat(id, name, el) {
    var val  = document.getElementById('fr-cats-val');
    var ids  = val.value ? val.value.split(',').filter(Boolean).map(Number) : [];
    var idx  = ids.indexOf(id);
    var cb   = el.querySelector('.gt-cat-cb');
    if(idx > -1) {
        ids.splice(idx,1);
        el.classList.remove('selected');
        cb.classList.remove('on');cb.innerHTML='';
    } else {
        ids.push(id);
        el.classList.add('selected');
        cb.classList.add('on');cb.innerHTML='<span style="color:#fff;font-size:9px;font-weight:800">✓</span>';
    }
    val.value=ids.join(',');
    frUpdateBadge('fr-cat-badge', ids.length);
}

function frFilterCats(val) {
    var v=val.toLowerCase();
    document.querySelectorAll('#fr-cat-list .gt-cat-item').forEach(function(el){
        el.style.display=el.dataset.name.toLowerCase().indexOf(v)>-1?'':'none';
    });
}

// ── Tags ───────────────────────────────────────────────────────────────────
function frToggleTag(id, name, el) {
    var val  = document.getElementById('fr-tags-val');
    var ids  = val.value ? val.value.split(',').filter(Boolean).map(Number) : [];
    var idx  = ids.indexOf(id);
    var cb   = el.querySelector('.gt-cat-cb');
    if(idx > -1) {
        ids.splice(idx,1);
        el.classList.remove('selected');
        cb.classList.remove('on');cb.style.background='';cb.style.borderColor='';cb.innerHTML='';
    } else {
        ids.push(id);
        el.classList.add('selected');
        cb.classList.add('on');cb.style.background='#22c55e';cb.style.borderColor='#22c55e';
        cb.innerHTML='<span style="color:#fff;font-size:9px;font-weight:800">✓</span>';
    }
    val.value=ids.join(',');
    frUpdateBadge('fr-tag-badge', ids.length);
}

function frFilterTags(val) {
    var v=val.toLowerCase();
    document.querySelectorAll('#fr-tag-list .gt-cat-item').forEach(function(el){
        el.style.display=el.dataset.name.toLowerCase().indexOf(v)>-1?'':'none';
    });
}

// ── Product type / stock / sale toggles ────────────────────────────────────
function frSetType(val, btn) {
    document.getElementById('fr-type-val').value=val;
    document.querySelectorAll('#fr-type-group .gt-tog-btn').forEach(function(b){b.classList.remove('on');});
    btn.classList.add('on');
    frCheckFilterBadge();
}
function frSetStock(val, btn) {
    document.getElementById('fr-stock-val').value=val;
    document.querySelectorAll('#fr-stock-group .gt-tog-btn').forEach(function(b){b.classList.remove('on');});
    btn.classList.add('on');
    frCheckFilterBadge();
}
function frSetSale(val, btn) {
    document.getElementById('fr-sale-val').value=val;
    document.querySelectorAll('#fr-sale-group .gt-tog-btn').forEach(function(b){b.classList.remove('on');});
    btn.classList.add('on');
    frCheckFilterBadge();
}
function frCheckFilterBadge() {
    var t=document.getElementById('fr-type-val').value;
    var s=document.getElementById('fr-stock-val').value;
    var o=document.getElementById('fr-sale-val').value;
    var badge=document.getElementById('fr-filter-badge');
    if(badge) badge.classList.toggle('active', !!(t||s||(o&&o!=='-1')));
}

// ── Badge helper ───────────────────────────────────────────────────────────
function frUpdateBadge(id, count) {
    var b=document.getElementById(id);
    if(!b) return;
    b.textContent=count+' selected';
    b.classList.toggle('active', count>0);
}

function gtFreeRuleOpenPicker(type) {
    var field    = document.getElementById('free-rule-' + type);
    var existing = field.value ? field.value.split(',').filter(Boolean).map(function(id){return {id:parseInt(id),name:'#'+id};}) : [];
    
    if(type === 'products' && existing.length) {
        // Load actual product names for existing IDs
        var fd = new FormData();
        fd.append('action','gtbogo_search_products');
        fd.append('nonce', _frNonce);
        fd.append('ids',   field.value);
        fetch(_frAjax,{method:'POST',body:fd,credentials:'same-origin'})
        .then(function(r){return r.json();})
        .then(function(res){
            if(res.success) existing = res.data.products;
            gtPickerOpen({nonce:_frNonce,ajaxUrl:_frAjax,mode:type,existingIds:existing,callback:function(items){
                gtFreeRuleApplyPicker(type,items);
            }});
        });
        return;
    }
    
    gtPickerOpen({nonce:_frNonce,ajaxUrl:_frAjax,mode:type,existingIds:existing,callback:function(items){
        gtFreeRuleApplyPicker(type,items);
    }});
}

function gtFreeRuleApplyPicker(type, items) {
    var field = document.getElementById('free-rule-' + type);
    var tags  = document.getElementById('free-rule-' + type + '-tags');
    field.value = items.map(function(i){return i.id;}).join(',');
    if(!items.length) {
        tags.innerHTML = '<span style="color:var(--gt-subtle);font-size:13px;padding:2px 4px">Click to select '+(type==='products'?'products':'categories')+'...</span>';
        return;
    }
    var color = type==='products' ? 'rgba(225,0,0,0.1)' : 'rgba(59,130,246,0.1)';
    var bcolor= type==='products' ? 'rgba(225,0,0,0.2)' : 'rgba(59,130,246,0.2)';
    tags.innerHTML = items.map(function(item){
        return '<span style="background:'+color+';border:1px solid '+bcolor+';border-radius:4px;padding:2px 8px;font-size:12px;color:#fff;display:flex;align-items:center;gap:4px">'
            + item.name
            + '<button type="button" onclick="event.stopPropagation();gtFreeRuleRemoveItem(''+type+'','+item.id+',this.parentNode)" style="background:none;border:none;color:#ef4444;cursor:pointer;padding:0;font-size:12px">&times;</button>'
            + '</span>';
    }).join('');
}

function gtFreeRuleRemoveItem(type, id, el) {
    if(el && el.parentNode) el.parentNode.removeChild(el);
    var field = document.getElementById('free-rule-' + type);
    var ids = field.value.split(',').filter(function(v){return v && parseInt(v) !== id;});
    field.value = ids.join(',');
    if(!ids.length) {
        var tags = document.getElementById('free-rule-' + type + '-tags');
        if(tags) tags.innerHTML = '<span style="color:var(--gt-subtle);font-size:13px;padding:2px 4px">Click to select '+(type==='products'?'products':'categories')+'...</span>';
    }
}
</script>

<!-- CART MESSAGING -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
    <div class="gt-card-header"><h2 class="gt-card-title">💬 Cart Notification</h2></div>

    <div class="gt-setting-row">
        <div><div class="gt-setting-label">Show Cart Progress Message</div><div class="gt-setting-desc">Display a message in the cart when the customer is close to qualifying. Encourages customers to add another item.</div></div>
        <label class="gt-toggle"><input type="checkbox" name="notify_cart" value="1" <?php checked(!empty($r['notify_cart'])); ?>><span class="gt-toggle-track"><span class="gt-toggle-thumb"></span></span></label>
    </div>
    <div class="gt-form-group" style="margin-top:12px">
        <label class="gt-form-label">Cart Message</label>
        <input type="text" name="cart_message" class="gt-input" value="<?php echo esc_attr($r['cart_message']); ?>" placeholder="Add another item to claim your complimentary product.">
        <div class="gt-form-hint">Shown above the cart when the customer has not yet qualified. Keep under 100 characters. Use neutral language — no exclamation marks.</div>
    </div>
</div>

<!-- PRODUCT BADGE -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
    <div class="gt-card-header"><h2 class="gt-card-title">🏷️ Product Badge</h2></div>
    <div class="gt-setting-row">
        <div><div class="gt-setting-label">Show Badge on Eligible Products</div><div class="gt-setting-desc">Display a small badge on product images for items that can trigger this BOGO rule. Inherits your theme styling.</div></div>
        <label class="gt-toggle"><input type="checkbox" name="show_badge" value="1" <?php checked(!empty($r['show_badge'])); ?>><span class="gt-toggle-track"><span class="gt-toggle-thumb"></span></span></label>
    </div>
    <div class="gt-form-group" style="margin-top:12px">
        <label class="gt-form-label">Badge Text</label>
        <input type="text" name="badge_text" class="gt-input" style="max-width:200px" value="<?php echo esc_attr($r['badge_text']); ?>" placeholder="Deal" maxlength="16">
        <div class="gt-form-hint">Short label on the product badge. Keep under 12 characters.</div>
    </div>
</div>

<!-- PRO UPGRADE CTA -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px;background:linear-gradient(135deg,rgba(225,0,0,0.06),rgba(7,12,28,0));border-color:rgba(225,0,0,0.2)">
    <div class="gt-card-header"><h2 class="gt-card-title">🚀 Unlock the Full Power</h2></div>
    <p style="font-size:13px;color:var(--gt-soft);margin-bottom:16px">The Free Rule handles one store-wide BOGO. PRO gives you unlimited rules with precision targeting, scheduling, and enterprise controls.</p>
    <div class="gt-feature-grid gt-feature-grid--3col" style="margin-bottom:20px">
        <?php foreach([
            ['🎯','Unlimited PRO Rules','Category and product-level targeting, multiple simultaneous campaigns'],
            ['⏰','Campaign Scheduler','Set start and end dates, day-of-week schedules, and time-of-day windows'],
            ['🌍','Geo Targeting',     'Run different deals in different countries, states, or postcodes'],
            ['🎨','Variant Rules',     'Target specific sizes, colours, and materials'],
            ['💱','Multi-Currency',    'Per-currency thresholds and discount caps for global stores'],
            ['📊','Full Analytics',    'Rule leaderboard, daily charts, peak hour heatmap, CSV export'],
        ] as $f): ?>
        <div style="padding:14px;border-radius:10px;background:rgba(255,255,255,0.02);border:1px solid var(--gt-border)">
            <div style="font-size:20px;margin-bottom:6px"><?php echo esc_html( $f[0] ); ?></div>
            <div style="font-size:13px;font-weight:700;color:var(--gt-white);margin-bottom:4px"><?php echo esc_html($f[1]); ?></div>
            <div style="font-size:13px;color:var(--gt-soft);line-height:1.5"><?php echo esc_html($f[2]); ?></div>
        </div>
        <?php endforeach; ?>
    </div>
    <?php if (!$is_pro): ?>
    <div style="display:flex;gap:12px;justify-content:center">
        <a href="https://graphictshirts.shop/bogo/" target="_blank" rel="noopener" class="gt-btn gt-btn-primary" style="padding:14px 36px">Upgrade to PRO — $149/yr</a>
        <a href="<?php echo esc_url(admin_url('admin.php?page=gt-bogo-engine&tab=license')); ?>" class="gt-btn gt-btn-ghost">Activate License</a>
    </div>
    <?php else: ?>
    <div style="text-align:center"><a href="<?php echo esc_url(admin_url('admin.php?page=gt-bogo-engine&tab=pro-rules')); ?>" class="gt-btn gt-btn-primary" style="padding:12px 32px">Go to PRO Rules →</a></div>
    <?php endif; ?>
</div>

<div style="text-align:right">
    <button type="submit" name="gtbogo_save_free_rule" class="gt-btn gt-btn-primary" style="padding:14px 40px">💾 Save Free Rule</button>
</div>
</form>

<!-- GUIDANCE -->
<div class="gt-card gt-animate-in" style="background:linear-gradient(135deg,rgba(59,130,246,0.06),rgba(7,12,28,0));border-color:rgba(59,130,246,0.15);margin-top:20px">
    <div class="gt-card-header"><h2 class="gt-card-title">🧠 Free Rule Best Practices</h2></div>
    <div class="gt-feature-grid gt-feature-grid--2col">
        <div><div style="font-size:13px;font-weight:700;color:var(--gt-white);margin-bottom:6px">Start With a Minimum Cart Total</div><div style="font-size:13px;color:var(--gt-soft);line-height:1.7">Set a minimum cart total of at least your average product price to prevent the deal from firing on very small orders. A $25 minimum on a store with a $30 average product price means nearly every order qualifies while still protecting against discount exploitation on low-value baskets.</div></div>
        <div><div style="font-size:13px;font-weight:700;color:var(--gt-white);margin-bottom:6px">Cheapest Item = Best Margin Protection</div><div style="font-size:13px;color:var(--gt-soft);line-height:1.7">Apply the discount to the cheapest item in the cart. This means customers who add your most expensive product to get a cheap item discounted — rather than getting your hero product free. It drives up AOV while minimising discount cost as a percentage of revenue.</div></div>
        <div><div style="font-size:13px;font-weight:700;color:var(--gt-white);margin-bottom:6px">Cart Message Drives Qualification</div><div style="font-size:13px;color:var(--gt-soft);line-height:1.7">A well-written cart message is worth an estimated 8–12% increase in qualification rate. "Add one more item to receive a complimentary product" is more effective than "Add to get BOGO" because it implies the customer is close to something valuable — not that they need to do work.</div></div>
        <div><div style="font-size:13px;font-weight:700;color:var(--gt-white);margin-bottom:6px">Exclude Sale Items to Protect Margin</div><div style="font-size:13px;color:var(--gt-soft);line-height:1.7">Always enable "Exclude Sale-Priced Items" unless you are running an intentional clearance event. Without this, customers can trigger BOGO on items already discounted 40–50%, resulting in an effective discount of 70%+ that can push the order margin negative.</div></div>
    </div>
</div>

<?php require_once __DIR__ . '/../ui-system/wrapper-end.php'; ?>
