<?php
// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals
// phpcs:disable WordPress.Security.NonceVerification
// phpcs:disable WordPress.Security.ValidatedSanitizedInput
// phpcs:disable WordPress.DB.DirectDatabaseQuery
// phpcs:disable WordPress.DB.SlowDBQuery
// phpcs:disable WordPress.DB.PreparedSQL
// phpcs:disable PluginCheck.CodeAnalysis
// phpcs:disable WordPressVIPMinimum
/**
 * GT BOGO Engine — Free Core Rule
 *
 * Complete enterprise free rule configuration:
 *   - Rule enable/disable (AJAX instant, no page reload)
 *   - Deal structure: buy qty, get qty, discount type/value, apply-to, min cart, max uses
 *   - Live deal preview (updates as you type)
 *   - Product targeting: AJAX live search with filters (category, type, stock, sale, sort)
 *   - Category targeting: PHP-rendered checkboxes with live filter search
 *   - Tag targeting: PHP-rendered checkboxes with live filter search
 *   - Product filter toggles: type / stock / sale status
 *   - Scheduling: start date, end date, rule priority
 *   - Cart notification message
 *   - 30-day analytics KPIs
 *   - PRO upgrade CTA
 *   - Free rule best practices guide
 *
 * Saves to: gtbogo_free_rule (array) + individual gt_bogo_free_rule_* options
 * Engine reads: gt_bogo_free_rule_* options
 * AJAX nonce: gtbogo_product_search (all product/category search + field autosave)
 *
 * @package GT_BOGO_Engine
 * @since   5.0.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;
$version = defined( 'GT_BOGO_VERSION' ) ? GT_BOGO_VERSION : '5.0.0';
$message = '';

global $wpdb;

/* ── Save handler ────────────────────────────────────────────────────────── */
if ( isset( $_POST['gtbogo_save_free_rule'] ) && check_admin_referer( 'gtbogo_free_rule' ) ) {

    $cats_raw  = sanitize_text_field( wp_unslash( $_POST['rule_categories'] ?? '' ) );
    $prods_raw = sanitize_text_field( wp_unslash( $_POST['rule_products']   ?? '' ) );
    $tags_raw  = sanitize_text_field( wp_unslash( $_POST['rule_tags']       ?? '' ) );
    $cat_ids   = array_values( array_filter( array_map( 'absint', explode( ',', $cats_raw  ) ) ) );
    $prod_ids  = array_values( array_filter( array_map( 'absint', explode( ',', $prods_raw ) ) ) );
    $tag_ids   = array_values( array_filter( array_map( 'absint', explode( ',', $tags_raw  ) ) ) );

    $data = [
        'enabled'           => isset( $_POST['free_enabled'] ),
        'buy_quantity'      => max( 1, min( 99, absint( $_POST['buy_quantity']      ?? 1 ) ) ),
        'get_quantity'      => max( 1, min( 99, absint( $_POST['get_quantity']      ?? 1 ) ) ),
        'discount_type'     => in_array( $_POST['discount_type'] ?? '', ['percentage','fixed'], true )
                               ? sanitize_key( wp_unslash( $_POST['discount_type'] ) ) : 'percentage',
        'discount_value'    => (float) ( $_POST['discount_value']    ?? 100 ),
        'apply_to'          => sanitize_key( wp_unslash( $_POST['apply_to']         ?? 'cheapest' ) ),
        'min_cart_total'    => (float) ( $_POST['min_cart_total']    ?? 0 ),
        'max_uses_per_cart' => max( 1, absint( $_POST['max_uses_per_cart'] ?? 1 ) ),
        'title'             => sanitize_text_field( wp_unslash( $_POST['rule_title']  ?? 'Buy One Get One' ) ),
        'description'       => sanitize_textarea_field( wp_unslash( $_POST['rule_desc'] ?? '' ) ),
        'exclude_sale'      => isset( $_POST['exclude_sale'] ),
        'notify_cart'       => isset( $_POST['notify_cart'] ),
        'cart_message'      => sanitize_text_field( wp_unslash( $_POST['cart_message'] ?? '' ) ),
        'categories'        => $cat_ids,
        'products'          => $prod_ids,
        'tags'              => $tag_ids,
        'product_type'      => sanitize_key( wp_unslash( $_POST['rule_product_type'] ?? '' ) ),
        'stock_status'      => sanitize_key( wp_unslash( $_POST['rule_stock_status'] ?? '' ) ),
        'on_sale'           => (int) ( $_POST['rule_on_sale'] ?? -1 ),
        'priority'          => max( 1, absint( $_POST['rule_priority'] ?? 50 ) ),
        'start_date'        => sanitize_text_field( wp_unslash( $_POST['rule_start_date'] ?? '' ) ),
        'end_date'          => sanitize_text_field( wp_unslash( $_POST['rule_end_date']   ?? '' ) ),
        'updated'           => current_time( 'mysql', true ),
    ];

    /* Main option blob */
    update_option( 'gtbogo_free_rule', $data );

    /* Individual option sync — these are what the engine reads */
    update_option( 'gt_bogo_free_rule_enabled',       (int) $data['enabled'] );
    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_deal_mode',       in_array( $_POST['deal_mode'] ?? 'discount', ['discount','value_add'], true ) ? $_POST['deal_mode'] : 'discount' );
    update_option( 'gt_bogo_free_rule_value_add_label', sanitize_text_field( wp_unslash( $_POST['value_add_label'] ?? 'complimentary gift' ) ) );
    update_option( 'gt_bogo_free_rule_exclude_sale',   (int) $data['exclude_sale'] );
    update_option( 'gt_bogo_free_rule_categories',     $cat_ids );
    update_option( 'gt_bogo_free_rule_products',       $prod_ids );
    update_option( 'gt_bogo_free_rule_tags',           $tag_ids );
    update_option( 'gt_bogo_free_rule_start_date',     $data['start_date'] );
    update_option( 'gt_bogo_free_rule_end_date',       $data['end_date'] );
    update_option( 'gt_bogo_free_rule_notify_cart',    (int) $data['notify_cart'] );
    update_option( 'gt_bogo_free_rule_cart_message',   $data['cart_message'] );
    update_option( 'gt_bogo_free_rule_initialized',    1 );

    /* Sync to rules table for analytics */
    $rules_tbl = $wpdb->prefix . 'gtbogo_rules';
    if ( $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $rules_tbl ) ) ) { // phpcs:ignore
        $existing = (int) $wpdb->get_var( $wpdb->prepare( // phpcs:ignore
            "SELECT id FROM {$rules_tbl} WHERE pack_source='free_rule' LIMIT 1"
        ) );
        $rule_row = [
            'name'          => $data['title'],
            'buy_qty'       => $data['buy_quantity'],
            'get_qty'       => $data['get_quantity'],
            'discount_type' => $data['discount_type'],
            'discount_value'=> $data['discount_value'],
            'status'        => $data['enabled'] ? 'active' : 'inactive',
            'pack_source'   => 'free_rule',
            'updated_at'    => current_time( 'mysql', true ),
        ];
        if ( $existing ) {
            $wpdb->update( $rules_tbl, $rule_row, ['id' => $existing] ); // phpcs:ignore
            update_option( 'gtbogo_free_rule_db_id', $existing ); /* BUG-5: wire free rule to analytics */
        } else {
            $rule_row['created_at'] = current_time( 'mysql', true );
            $wpdb->insert( $rules_tbl, $rule_row ); // phpcs:ignore
            update_option( 'gtbogo_free_rule_db_id', (int) $wpdb->insert_id ); /* BUG-5 */
        }
    }

    if ( function_exists( 'gt_bogo_engine_flush_cache' ) ) gt_bogo_engine_flush_cache();
    delete_transient( 'gtbogo_active_rules' );

    $message = 'Free rule saved. Changes apply on the next cart load.';
}

/* ── Load saved settings ─────────────────────────────────────────────────── */
$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,
    'notify_cart'       => true,
    'cart_message'      => 'Add another item to claim your complimentary product.',
    'categories'        => [],
    'products'          => [],
    'tags'              => [],
    'product_type'      => '',
    'stock_status'      => '',
    'on_sale'           => -1,
    'priority'          => 50,
    'start_date'        => '',
    'end_date'          => '',
] );

/* ── Analytics (30d) ─────────────────────────────────────────────────────── */
$outcomes_tbl = $wpdb->prefix . 'gtbogo_outcomes';
$stats        = [ 'fires'=>0,'accepted'=>0,'deal_value'=>0,'margin'=>0 ];
if ( $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $outcomes_tbl ) ) ) { // phpcs:ignore
    $rules_tbl = $wpdb->prefix . 'gtbogo_rules';
    $free_rule_id = 0;
    if ( $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $rules_tbl ) ) ) { // phpcs:ignore
        $free_rule_id = (int) $wpdb->get_var( $wpdb->prepare( // phpcs:ignore
            "SELECT id FROM {$rules_tbl} WHERE pack_source='free_rule' LIMIT 1"
        ) );
    }
    if ( $free_rule_id ) {
        $stats['fires']      = (int) $wpdb->get_var( $wpdb->prepare( // phpcs:ignore
            "SELECT COUNT(*) FROM {$outcomes_tbl} WHERE rule_id=%d AND event_type='deal_fired' AND fired_at>=DATE_SUB(UTC_TIMESTAMP(),INTERVAL 30 DAY)", $free_rule_id
        ) );
        $stats['accepted']   = (int) $wpdb->get_var( $wpdb->prepare( // phpcs:ignore
            "SELECT COUNT(*) FROM {$outcomes_tbl} WHERE rule_id=%d AND event_type='deal_accepted' AND fired_at>=DATE_SUB(UTC_TIMESTAMP(),INTERVAL 30 DAY)", $free_rule_id
        ) );
        $stats['deal_value'] = (float) $wpdb->get_var( $wpdb->prepare( // phpcs:ignore
            "SELECT SUM(deal_value) FROM {$outcomes_tbl} WHERE rule_id=%d AND event_type='deal_accepted' AND fired_at>=DATE_SUB(UTC_TIMESTAMP(),INTERVAL 30 DAY)", $free_rule_id
        ) );
    }
}
$conv_rate = $stats['fires'] > 0 ? round( $stats['accepted'] / $stats['fires'] * 100, 1 ) : 0;

/* ── Saved selections ────────────────────────────────────────────────────── */
$saved_cat_ids  = array_values( array_filter( array_map( 'absint', (array)($r['categories']   ?? []) ) ) );
$saved_prod_ids = array_values( array_filter( array_map( 'absint', (array)($r['products']     ?? []) ) ) );
$saved_tag_ids  = array_values( array_filter( array_map( 'absint', (array)($r['tags']         ?? []) ) ) );
$saved_type     = sanitize_key( $r['product_type']  ?? '' );
$saved_stock    = sanitize_key( $r['stock_status']  ?? '' );
$saved_on_sale  = (int) ( $r['on_sale']  ?? -1 );

/* ── All categories + tags for rendering ────────────────────────────────── */
$all_cats = get_terms( [ 'taxonomy'=>'product_cat', 'hide_empty'=>false, 'orderby'=>'name', 'number'=>0 ] );
$all_tags = get_terms( [ 'taxonomy'=>'product_tag', 'hide_empty'=>true,  'orderby'=>'count', 'order'=>'DESC', 'number'=>200 ] );

/* ── Saved product names ─────────────────────────────────────────────────── */
$saved_products = [];
foreach ( $saved_prod_ids as $pid ) {
    $p = function_exists('wc_get_product') ? wc_get_product( $pid ) : null;
    if ( $p ) $saved_products[] = [ 'id'=>$pid, 'name'=>$p->get_name() ];
}

/* ── Nonce ───────────────────────────────────────────────────────────────── */
$search_nonce = wp_create_nonce( 'gtbogo_product_search' );
$enable_nonce = wp_create_nonce( 'gtbogo_product_search' ); /* same nonce — autosave_free_rule_field uses gtbogo_product_search */

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

<!-- ═══════════════════════════════════════════════════════════════════════
     PAGE HEADER
════════════════════════════════════════════════════════════════════════ -->
<div class="gt-page-header gt-animate-in" style="align-items:flex-start">
    <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 product targeting, live search, scheduling, and cart messaging.
        </p>
    </div>
    <div style="display:flex;gap:8px;align-items:center;flex-wrap:wrap">
        <span class="gt-badge <?php echo !empty($r['enabled'])?'gt-badge-active':'gt-badge-free'; ?>"
              id="gt-fr-status-badge">
            <?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>
        <?php if (!$is_pro) : ?>
        <a href="<?php echo esc_url(admin_url('admin.php?page=gt-bogo-engine&tab=license')); ?>"
           class="gt-btn gt-btn-primary gt-btn-sm">Upgrade to PRO →</a>
        <?php endif; ?>
    </div>
</div>

<?php if ($message) : ?>
<div class="gt-notice gt-notice-success gt-animate-in">✓ <?php echo esc_html($message); ?></div>
<?php endif; ?>

<!-- ═══════════════════════════════════════════════════════════════════════
     ANALYTICS KPIs
════════════════════════════════════════════════════════════════════════ -->
<div class="gt-animate-in" style="display:grid;grid-template-columns:repeat(4,1fr);gap:14px;margin-bottom:20px">
    <?php
    $cr_c = $conv_rate>=30?'#22c55e':($conv_rate>=15?'#f59e0b':'var(--gt-subtle)');
    $kpis = [
        ['Rule Status', !empty($r['enabled'])?'Active':'Inactive', !empty($r['enabled'])?'#22c55e':'#64748b', 'Buy '.(int)$r['buy_quantity'].' Get '.(int)$r['get_quantity'].' — '.(float)$r['discount_value'].($r['discount_type']==='percentage'?'%':'$').' off'],
        ['Fires (30d)', number_format($stats['fires']), '#3b82f6', 'deal_fired events'],
        ['Conversions (30d)', number_format($stats['accepted']), '#22c55e', 'deal_accepted events'],
        ['Conv. Rate', $conv_rate.'%', $cr_c, 'accepted ÷ fired'],
    ];
    foreach ($kpis as $k) : ?>
    <div class="gt-card" style="padding:18px 20px;text-align:center">
        <div style="font-size:26px;font-weight:900;color:<?php echo esc_attr($k[2]); ?>;margin-bottom:4px;line-height:1">
            <?php echo esc_html($k[1]); ?>
        </div>
        <div style="font-size:10px;font-weight:800;letter-spacing:.1em;text-transform:uppercase;color:var(--gt-subtle)">
            <?php echo esc_html($k[0]); ?>
        </div>
        <div style="font-size:10px;color:rgba(100,116,139,0.6);margin-top:2px"><?php echo esc_html($k[3]); ?></div>
    </div>
    <?php endforeach; ?>
</div>

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

<!-- ═══════════════════════════════════════════════════════════════════════
     RULE STATUS
════════════════════════════════════════════════════════════════════════ -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
    <div class="gt-setting-row" style="border:none;padding:0">
        <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.
                Changes save instantly — the toggle auto-saves without a page reload.
            </div>
        </div>
        <label class="gt-toggle">
            <input type="checkbox" name="free_enabled" value="1" id="gt-fr-enabled"
                   <?php checked(!empty($r['enabled'])); ?>>
            <span class="gt-toggle-track"><span class="gt-toggle-thumb"></span></span>
        </label>
    </div>
    <div id="gt-fr-enable-status" style="font-size:11px;color:var(--gt-subtle);margin-top:6px;min-height:16px"></div>
</div>

<!-- ═══════════════════════════════════════════════════════════════════════
     RULE IDENTITY
════════════════════════════════════════════════════════════════════════ -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
    <div class="gt-card-header"><h2 class="gt-card-title">🏷️ Rule Identity</h2></div>
    <div style="display:grid;grid-template-columns:1fr 1fr;gap:16px">
        <div class="gt-form-group" style="margin:0">
            <label class="gt-form-label">Rule Display Name</label>
            <input type="text" name="rule_title" class="gt-input" id="gt-fr-title"
                   value="<?php echo esc_attr($r['title']); ?>"
                   placeholder="Buy One Get One"
                   oninput="gtFrUpdatePreview()">
            <div class="gt-form-hint">Shown in cart, analytics, and email notifications</div>
        </div>
        <div class="gt-form-group" style="margin:0">
            <label class="gt-form-label">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 TYPE (GAP 3: Value-Add) ─────────────────────────────────────────── -->
<div class="gt-card" style="margin-bottom:20px">
    <div class="gt-card-header"><h2 class="gt-card-title">&#127873; Deal Presentation</h2></div>
    <div style="padding:16px 20px">
        <div class="gt-form-group" style="margin-bottom:16px">
            <label class="gt-form-label">Deal Mode</label>
            <div style="display:flex;gap:16px;flex-wrap:wrap">
                <label style="display:flex;align-items:center;gap:8px;cursor:pointer;padding:10px 16px;border:1px solid var(--gt-border);border-radius:8px;background:var(--gt-bg-card)">
                    <input type="radio" name="deal_mode" value="discount" style="width:auto;accent-color:var(--gt-red)"
                           <?php checked( get_option( 'gt_bogo_free_rule_deal_mode', 'discount' ), 'discount' ); ?>>
                    <span>
                        <strong style="display:block;font-size:13px">Discount</strong>
                        <span style="font-size:12px;color:var(--gt-subtle)">Shows percentage or fixed price reduction in cart</span>
                    </span>
                </label>
                <label style="display:flex;align-items:center;gap:8px;cursor:pointer;padding:10px 16px;border:1px solid var(--gt-border);border-radius:8px;background:var(--gt-bg-card)">
                    <input type="radio" name="deal_mode" value="value_add" style="width:auto;accent-color:var(--gt-red)"
                           <?php checked( get_option( 'gt_bogo_free_rule_deal_mode', 'discount' ), 'value_add' ); ?>
                           onchange="document.getElementById('gt-va-label-row').style.display='block'"
                           >
                    <span>
                        <strong style="display:block;font-size:13px">Value-Add (Luxury)</strong>
                        <span style="font-size:12px;color:var(--gt-subtle)">Shows "Complimentary [service]" — no price reduction visible</span>
                    </span>
                </label>
            </div>
            <div class="gt-form-hint">Luxury and premium brands use Value-Add to avoid discount optics. Gucci-tier appropriate.</div>
        </div>
        <div id="gt-va-label-row" style="<?php echo get_option('gt_bogo_free_rule_deal_mode','discount')==='value_add'?'':'display:none'; ?>">
            <label class="gt-form-label">Complimentary Service / Gift Label</label>
            <input type="text" name="value_add_label" class="gt-input" style="max-width:320px"
                   value="<?php echo esc_attr( get_option( 'gt_bogo_free_rule_value_add_label', 'complimentary gift' ) ); ?>"
                   placeholder="e.g. engraving, gift wrapping, fragrance consultation, monogramming">
            <div class="gt-form-hint">Cart shows: "Complimentary [your label]" — suitable for Gucci, Rolex, Chanel</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>
        <span style="font-size:12px;color:var(--gt-subtle)">Preview updates live as you type</span>
    </div>

    <div style="display:grid;grid-template-columns:repeat(4,1fr);gap:16px;margin-bottom:16px">
        <div class="gt-form-group" style="margin:0">
            <label class="gt-form-label">Buy Quantity</label>
            <input type="number" name="buy_quantity" class="gt-input" id="gt-fr-buy-qty"
                   value="<?php echo esc_attr((string)(int)$r['buy_quantity']); ?>"
                   min="1" max="99" oninput="gtFrUpdatePreview()">
            <div class="gt-form-hint">Items customer must add to cart</div>
        </div>
        <div class="gt-form-group" style="margin:0">
            <label class="gt-form-label">Get Quantity</label>
            <input type="number" name="get_quantity" class="gt-input" id="gt-fr-get-qty"
                   value="<?php echo esc_attr((string)(int)$r['get_quantity']); ?>"
                   min="1" max="99" oninput="gtFrUpdatePreview()">
            <div class="gt-form-hint">Items that receive the discount</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" id="gt-fr-disc-type"
                    onchange="gtFrUpdatePreview()">
                <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" id="gt-fr-disc-val"
                   value="<?php echo esc_attr((string)(float)$r['discount_value']); ?>"
                   min="0.01" max="100" step="0.01" oninput="gtFrUpdatePreview()">
            <div class="gt-form-hint">100% = fully free</div>
        </div>
    </div>

    <div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:16px;margin-bottom:16px">
        <div class="gt-form-group" style="margin:0">
            <label class="gt-form-label">Apply Discount To</label>
            <select name="apply_to" class="gt-select" id="gt-fr-apply-to"
                    onchange="gtFrUpdatePreview()">
                <option value="cheapest"   <?php selected($r['apply_to'],'cheapest'); ?>>Cheapest item (best margin)</option>
                <option value="cheapest_n" <?php selected($r['apply_to'],'cheapest_n'); ?>>N cheapest items</option>
                <option value="most_exp"   <?php selected($r['apply_to'],'most_exp'); ?>>Most expensive item</option>
                <?php if ($is_pro) : ?>
                <option value="specific"   <?php selected($r['apply_to'],'specific'); ?>>Specific product (PRO)</option>
                <?php else : ?>
                <option value="specific" disabled style="color:#475569">Specific product (PRO)</option>
                <?php endif; ?>
            </select>
        </div>
        <div class="gt-form-group" style="margin:0">
            <label class="gt-form-label">Minimum Cart Total ($)</label>
            <input type="number" name="min_cart_total" class="gt-input" id="gt-fr-min-cart"
                   value="<?php echo esc_attr((string)(float)$r['min_cart_total']); ?>"
                   min="0" step="0.01" placeholder="0.00" oninput="gtFrUpdatePreview()">
            <div class="gt-form-hint">0 = no minimum required</div>
        </div>
        <div class="gt-form-group" style="margin:0">
            <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((string)(int)$r['max_uses_per_cart']); ?>"
                   min="1" max="99">
            <div class="gt-form-hint">How many times the deal stacks in one 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">BOGO does not apply to products already on sale — prevents compounding discounts</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>

    <!-- Live Deal Preview -->
    <div style="margin-top:16px;padding:18px 20px;background:rgba(225,0,0,0.04);border:1px solid rgba(225,0,0,0.15);border-radius:10px;text-align:center">
        <div id="gt-fr-preview-headline"
             style="font-size:20px;font-weight:900;color:var(--gt-white);margin-bottom:6px;line-height:1.2">
            Buy 1 Get 1 — 100% Off
        </div>
        <div id="gt-fr-preview-sub"
             style="font-size:12px;color:var(--gt-subtle)">
            Cheapest eligible item receives the discount. No minimum cart required.
        </div>
    </div>
</div>

<!-- ═══════════════════════════════════════════════════════════════════════
     TARGETING
════════════════════════════════════════════════════════════════════════ -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
    <div class="gt-card-header">
        <h2 class="gt-card-title">🎯 Targeting</h2>
        <span style="font-size:12px;color:var(--gt-subtle)">
            Empty = all products · Mix products + categories = union (either qualifies)
        </span>
    </div>

    <!-- Hidden inputs that hold the selected IDs -->
    <input type="hidden" name="rule_products"     id="gt-fr-products-val"  value="<?php echo esc_attr(implode(',', $saved_prod_ids)); ?>">
    <input type="hidden" name="rule_categories"   id="gt-fr-cats-val"      value="<?php echo esc_attr(implode(',', $saved_cat_ids)); ?>">
    <input type="hidden" name="rule_tags"         id="gt-fr-tags-val"      value="<?php echo esc_attr(implode(',', $saved_tag_ids)); ?>">
    <input type="hidden" name="rule_product_type" id="gt-fr-type-val"      value="<?php echo esc_attr($saved_type); ?>">
    <input type="hidden" name="rule_stock_status" id="gt-fr-stock-val"     value="<?php echo esc_attr($saved_stock); ?>">
    <input type="hidden" name="rule_on_sale"      id="gt-fr-sale-val"      value="<?php echo esc_attr((string)$saved_on_sale); ?>">

    <!-- ── PRODUCTS accordion ──────────────────────────────────── -->
    <div class="gt-fr-section" style="border:1px solid var(--gt-border);border-radius:8px;overflow:hidden;margin-bottom:10px">
        <div class="gt-fr-hdr" onclick="gtFrAccordion(this)"
             style="display:flex;align-items:center;justify-content:space-between;padding:12px 16px;cursor:pointer;user-select:none;background:rgba(255,255,255,0.02)">
            <div style="display:flex;align-items:center;gap:10px">
                <span style="font-size:18px">📦</span>
                <span style="font-size:13px;font-weight:700;color:var(--gt-white)">Specific Products</span>
                <span class="gt-fr-badge" id="gt-fr-prod-badge"
                      style="display:none;padding:1px 8px;border-radius:20px;font-size:10px;font-weight:800;
                             background:rgba(225,0,0,0.12);border:1px solid rgba(225,0,0,0.2);color:var(--gt-red)">
                    <?php echo esc_html((string)count($saved_products)); ?> selected
                </span>
            </div>
            <div style="display:flex;align-items:center;gap:8px">
                <span style="font-size:11px;color:var(--gt-subtle)">Empty = any product</span>
                <span class="gt-fr-arrow" style="color:var(--gt-subtle);font-size:11px;transition:transform .2s">▲</span>
            </div>
        </div>
        <div class="gt-fr-body" style="padding:14px 16px">
            <!-- Selected product tags -->
            <div id="gt-fr-prod-tags" style="display:flex;flex-wrap:wrap;gap:6px;margin-bottom:10px;min-height:4px">
                <?php foreach ($saved_products as $sp) : ?>
                <span style="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:var(--gt-white)"
                      data-id="<?php echo esc_attr((string)$sp['id']); ?>">
                    <?php echo esc_html($sp['name']); ?>
                    <button type="button"
                            onclick="gtFrRemoveProduct(<?php echo esc_attr((string)$sp['id']); ?>,this.parentNode)"
                            style="background:none;border:none;color:#94a3b8;cursor:pointer;padding:0;font-size:14px;line-height:1">×</button>
                </span>
                <?php endforeach; ?>
            </div>

            <!-- Search input -->
            <div style="position:relative;margin-bottom:8px">
                <span style="position:absolute;left:12px;top:50%;transform:translateY(-50%);color:#475569;font-size:14px;pointer-events:none">🔍</span>
                <input type="text" id="gt-fr-prod-search"
                       placeholder="Search products by name or SKU…"
                       autocomplete="off"
                       oninput="gtFrProductSearch(this.value)"
                       style="width:100%;padding:9px 12px 9px 36px;background:rgba(255,255,255,0.04);
                              border:1px solid var(--gt-border-md);border-radius:7px;color:var(--gt-white);
                              font-size:13px;box-sizing:border-box;outline:none;font-family:inherit"
                       onfocus="this.style.borderColor='rgba(225,0,0,0.4)'"
                       onblur="this.style.borderColor='var(--gt-border-md)'">
            </div>

            <!-- Filters row -->
            <div style="display:flex;gap:6px;flex-wrap:wrap;margin-bottom:8px">
                <select id="gt-fr-cat-filter" onchange="gtFrProductSearch(document.getElementById('gt-fr-prod-search').value)"
                        style="padding:5px 10px;background:var(--gt-card);border:1px solid var(--gt-border-md);border-radius:6px;color:var(--gt-white);font-size:12px;font-family:inherit;cursor:pointer">
                    <option value="">All Categories</option>
                    <?php if (!is_wp_error($all_cats)) : foreach ((array)$all_cats as $cat) : ?>
                    <option value="<?php echo esc_attr((string)$cat->term_id); ?>"><?php echo esc_html($cat->name); ?> (<?php echo esc_html((string)$cat->count); ?>)</option>
                    <?php endforeach; endif; ?>
                </select>
                <select id="gt-fr-type-filter" onchange="gtFrProductSearch(document.getElementById('gt-fr-prod-search').value)"
                        style="padding:5px 10px;background:var(--gt-card);border:1px solid var(--gt-border-md);border-radius:6px;color:var(--gt-white);font-size:12px;font-family:inherit;cursor:pointer">
                    <option value="">All Types</option>
                    <option value="simple">Simple</option>
                    <option value="variable">Variable</option>
                    <option value="grouped">Grouped</option>
                </select>
                <select id="gt-fr-stock-filter" onchange="gtFrProductSearch(document.getElementById('gt-fr-prod-search').value)"
                        style="padding:5px 10px;background:var(--gt-card);border:1px solid var(--gt-border-md);border-radius:6px;color:var(--gt-white);font-size:12px;font-family:inherit;cursor:pointer">
                    <option value="">Any Stock</option>
                    <option value="instock">In Stock</option>
                    <option value="outofstock">Out of Stock</option>
                </select>
                <select id="gt-fr-sale-filter" onchange="gtFrProductSearch(document.getElementById('gt-fr-prod-search').value)"
                        style="padding:5px 10px;background:var(--gt-card);border:1px solid var(--gt-border-md);border-radius:6px;color:var(--gt-white);font-size:12px;font-family:inherit;cursor:pointer">
                    <option value="">Any Sale Status</option>
                    <option value="1">On Sale Only</option>
                    <option value="0">Not On Sale</option>
                </select>
                <select id="gt-fr-sort" onchange="gtFrProductSearch(document.getElementById('gt-fr-prod-search').value)"
                        style="padding:5px 10px;background:var(--gt-card);border:1px solid var(--gt-border-md);border-radius:6px;color:var(--gt-white);font-size:12px;font-family:inherit;cursor:pointer">
                    <option value="title">A–Z</option>
                    <option value="date">Newest</option>
                    <option value="price">Price Low</option>
                    <option value="price-desc">Price High</option>
                    <option value="popularity">Popular</option>
                </select>
                <span id="gt-fr-prod-count" style="font-size:11px;color:var(--gt-subtle);align-self:center;margin-left:4px"></span>
            </div>

            <!-- Results -->
            <div id="gt-fr-prod-results"
                 style="max-height:240px;overflow-y:auto;border:1px solid var(--gt-border);border-radius:7px;background:var(--gt-card);display:none">
            </div>

            <!-- Pagination -->
            <div id="gt-fr-prod-pag" style="display:none;align-items:center;gap:8px;margin-top:6px;font-size:12px">
                <button type="button" id="gt-fr-prod-prev" onclick="gtFrProductPage(-1)"
                        style="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;font-family:inherit">← Prev</button>
                <span id="gt-fr-prod-pag-info" style="color:var(--gt-subtle)">Page 1</span>
                <button type="button" id="gt-fr-prod-next" onclick="gtFrProductPage(1)"
                        style="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;font-family:inherit">Next →</button>
            </div>
        </div>
    </div>

    <!-- ── CATEGORIES accordion ────────────────────────────────── -->
    <div class="gt-fr-section" style="border:1px solid var(--gt-border);border-radius:8px;overflow:hidden;margin-bottom:10px">
        <div class="gt-fr-hdr" onclick="gtFrAccordion(this)"
             style="display:flex;align-items:center;justify-content:space-between;padding:12px 16px;cursor:pointer;user-select:none;background:rgba(255,255,255,0.02)">
            <div style="display:flex;align-items:center;gap:10px">
                <span style="font-size:18px">🗂️</span>
                <span style="font-size:13px;font-weight:700;color:var(--gt-white)">Product Categories</span>
                <span class="gt-fr-badge" id="gt-fr-cat-badge"
                      style="display:<?php echo !empty($saved_cat_ids)?'inline-block':'none'; ?>;padding:1px 8px;border-radius:20px;font-size:10px;font-weight:800;background:rgba(59,130,246,0.12);border:1px solid rgba(59,130,246,0.2);color:#60a5fa">
                    <?php echo esc_html((string)count($saved_cat_ids)); ?> selected
                </span>
            </div>
            <div style="display:flex;align-items:center;gap:8px">
                <span style="font-size:11px;color:var(--gt-subtle)">Empty = all categories</span>
                <span class="gt-fr-arrow" style="color:var(--gt-subtle);font-size:11px;transition:transform .2s">▼</span>
            </div>
        </div>
        <div class="gt-fr-body" style="display:none;padding:14px 16px">
            <!-- Category search -->
            <input type="text" placeholder="Filter categories…"
                   oninput="gtFrFilterTerms('cat', this.value)"
                   style="width:100%;padding:7px 12px;background:rgba(255,255,255,0.04);border:1px solid var(--gt-border-md);
                          border-radius:7px;color:var(--gt-white);font-size:13px;box-sizing:border-box;
                          outline:none;font-family:inherit;margin-bottom:10px">
            <div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(180px,1fr));gap:5px;max-height:200px;overflow-y:auto"
                 id="gt-fr-cat-list">
                <?php if (!is_wp_error($all_cats)) : foreach ((array)$all_cats as $cat) :
                    $sel = in_array((int)$cat->term_id, $saved_cat_ids, true);
                ?>
                <div class="gt-fr-cat-item"
                     data-id="<?php echo esc_attr((string)$cat->term_id); ?>"
                     data-name="<?php echo esc_attr(strtolower($cat->name)); ?>"
                     onclick="gtFrToggleCat(<?php echo esc_attr((string)(int)$cat->term_id); ?>, this)"
                     style="display:flex;align-items:center;gap:8px;padding:7px 10px;border-radius:6px;cursor:pointer;
                            background:<?php echo $sel?'rgba(59,130,246,0.08)':'rgba(255,255,255,0.02)'; ?>;
                            border:1px solid <?php echo $sel?'rgba(59,130,246,0.25)':'var(--gt-border)'; ?>;
                            transition:all .15s">
                    <div class="gt-fr-cb"
                         style="width:16px;height:16px;border-radius:3px;flex-shrink:0;display:flex;align-items:center;justify-content:center;
                                background:<?php echo $sel?'#3b82f6':'var(--gt-card)'; ?>;
                                border:1.5px solid <?php echo $sel?'#3b82f6':'#475569'; ?>">
                        <?php if ($sel) : ?>
                        <span style="color:#fff;font-size:9px;font-weight:800">✓</span>
                        <?php endif; ?>
                    </div>
                    <span style="font-size:12px;color:var(--gt-white);flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">
                        <?php echo esc_html($cat->name); ?>
                    </span>
                    <span style="font-size:10px;color:var(--gt-subtle);flex-shrink:0"><?php echo esc_html((string)$cat->count); ?></span>
                </div>
                <?php endforeach; endif; ?>
            </div>
        </div>
    </div>

    <!-- ── TAGS accordion ──────────────────────────────────────── -->
    <?php if (!empty($all_tags) && !is_wp_error($all_tags)) : ?>
    <div class="gt-fr-section" style="border:1px solid var(--gt-border);border-radius:8px;overflow:hidden;margin-bottom:10px">
        <div class="gt-fr-hdr" onclick="gtFrAccordion(this)"
             style="display:flex;align-items:center;justify-content:space-between;padding:12px 16px;cursor:pointer;user-select:none;background:rgba(255,255,255,0.02)">
            <div style="display:flex;align-items:center;gap:10px">
                <span style="font-size:18px">🏷️</span>
                <span style="font-size:13px;font-weight:700;color:var(--gt-white)">Product Tags</span>
                <span class="gt-fr-badge" id="gt-fr-tag-badge"
                      style="display:<?php echo !empty($saved_tag_ids)?'inline-block':'none'; ?>;padding:1px 8px;border-radius:20px;font-size:10px;font-weight:800;background:rgba(34,197,94,0.12);border:1px solid rgba(34,197,94,0.3);color:#22c55e">
                    <?php echo esc_html((string)count($saved_tag_ids)); ?> selected
                </span>
            </div>
            <div style="display:flex;align-items:center;gap:8px">
                <span style="font-size:11px;color:var(--gt-subtle)">Target by tag</span>
                <span class="gt-fr-arrow" style="color:var(--gt-subtle);font-size:11px;transition:transform .2s">▼</span>
            </div>
        </div>
        <div class="gt-fr-body" style="display:none;padding:14px 16px">
            <input type="text" placeholder="Filter tags…"
                   oninput="gtFrFilterTerms('tag', this.value)"
                   style="width:100%;padding:7px 12px;background:rgba(255,255,255,0.04);border:1px solid var(--gt-border-md);
                          border-radius:7px;color:var(--gt-white);font-size:13px;box-sizing:border-box;
                          outline:none;font-family:inherit;margin-bottom:10px">
            <div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(180px,1fr));gap:5px;max-height:200px;overflow-y:auto"
                 id="gt-fr-tag-list">
                <?php foreach ((array)$all_tags as $tag) : if (is_wp_error($tag)) continue;
                    $sel = in_array((int)$tag->term_id, $saved_tag_ids, true);
                ?>
                <div class="gt-fr-tag-item"
                     data-id="<?php echo esc_attr((string)$tag->term_id); ?>"
                     data-name="<?php echo esc_attr(strtolower($tag->name)); ?>"
                     onclick="gtFrToggleTag(<?php echo esc_attr((string)(int)$tag->term_id); ?>, this)"
                     style="display:flex;align-items:center;gap:8px;padding:7px 10px;border-radius:6px;cursor:pointer;
                            background:<?php echo $sel?'rgba(34,197,94,0.08)':'rgba(255,255,255,0.02)'; ?>;
                            border:1px solid <?php echo $sel?'rgba(34,197,94,0.05)':'var(--gt-border)'; ?>;
                            transition:all .15s">
                    <div class="gt-fr-cb"
                         style="width:16px;height:16px;border-radius:3px;flex-shrink:0;display:flex;align-items:center;justify-content:center;
                                background:<?php echo $sel?'#22c55e':'var(--gt-card)'; ?>;
                                border:1.5px solid <?php echo $sel?'#22c55e':'#475569'; ?>">
                        <?php if ($sel) : ?>
                        <span style="color:#fff;font-size:9px;font-weight:800">✓</span>
                        <?php endif; ?>
                    </div>
                    <span style="font-size:12px;color:var(--gt-white);flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">
                        <?php echo esc_html($tag->name); ?>
                    </span>
                    <span style="font-size:10px;color:var(--gt-subtle);flex-shrink:0"><?php echo esc_html((string)$tag->count); ?></span>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
    </div>
    <?php endif; ?>

    <!-- ── PRODUCT FILTERS accordion ───────────────────────────── -->
    <div class="gt-fr-section" style="border:1px solid var(--gt-border);border-radius:8px;overflow:hidden">
        <div class="gt-fr-hdr" onclick="gtFrAccordion(this)"
             style="display:flex;align-items:center;justify-content:space-between;padding:12px 16px;cursor:pointer;user-select:none;background:rgba(255,255,255,0.02)">
            <div style="display:flex;align-items:center;gap:10px">
                <span style="font-size:18px">⚙️</span>
                <span style="font-size:13px;font-weight:700;color:var(--gt-white)">Product Filters</span>
                <span class="gt-fr-badge" id="gt-fr-filter-badge"
                      style="display:<?php echo ($saved_type||$saved_stock||$saved_on_sale>=0)?'inline-block':'none'; ?>;
                             padding:1px 8px;border-radius:20px;font-size:10px;font-weight:800;
                             background:rgba(245,158,11,0.12);border:1px solid rgba(245,158,11,0.2);color:#f59e0b">
                    Active
                </span>
            </div>
            <span class="gt-fr-arrow" style="color:var(--gt-subtle);font-size:11px;transition:transform .2s">▼</span>
        </div>
        <div class="gt-fr-body" style="display:none;padding:14px 16px">
            <div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:16px">
                <div>
                    <div class="gt-form-label" style="margin-bottom:8px">Product Type</div>
                    <div style="display:flex;flex-wrap:wrap;gap:5px" id="gt-fr-type-grp">
                        <?php foreach ([''=>'Any','simple'=>'Simple','variable'=>'Variable','grouped'=>'Grouped'] as $v=>$l) : ?>
                        <button type="button"
                                onclick="gtFrSetFilter('type','<?php echo esc_js($v); ?>',this)"
                                style="padding:5px 12px;border-radius:6px;font-size:12px;cursor:pointer;font-family:inherit;transition:all .15s;
                                       background:<?php echo $saved_type===$v?'rgba(225,0,0,0.1)':'rgba(255,255,255,0.03)'; ?>;
                                       border:1px solid <?php echo $saved_type===$v?'rgba(225,0,0,0.3)':'var(--gt-border)'; ?>;
                                       color:<?php echo $saved_type===$v?'var(--gt-white)':'#94a3b8'; ?>;font-weight:<?php echo $saved_type===$v?'700':'400'; ?>">
                            <?php echo esc_html($l); ?>
                        </button>
                        <?php endforeach; ?>
                    </div>
                </div>
                <div>
                    <div class="gt-form-label" style="margin-bottom:8px">Stock Status</div>
                    <div style="display:flex;flex-wrap:wrap;gap:5px" id="gt-fr-stock-grp">
                        <?php foreach ([''=>'Any','instock'=>'In Stock','outofstock'=>'Out of Stock'] as $v=>$l) : ?>
                        <button type="button"
                                onclick="gtFrSetFilter('stock','<?php echo esc_js($v); ?>',this)"
                                style="padding:5px 12px;border-radius:6px;font-size:12px;cursor:pointer;font-family:inherit;transition:all .15s;
                                       background:<?php echo $saved_stock===$v?'rgba(59,130,246,0.1)':'rgba(255,255,255,0.03)'; ?>;
                                       border:1px solid <?php echo $saved_stock===$v?'rgba(59,130,246,0.3)':'var(--gt-border)'; ?>;
                                       color:<?php echo $saved_stock===$v?'var(--gt-white)':'#94a3b8'; ?>;font-weight:<?php echo $saved_stock===$v?'700':'400'; ?>">
                            <?php echo esc_html($l); ?>
                        </button>
                        <?php endforeach; ?>
                    </div>
                </div>
                <div>
                    <div class="gt-form-label" style="margin-bottom:8px">Sale Status</div>
                    <div style="display:flex;flex-wrap:wrap;gap:5px" id="gt-fr-sale-grp">
                        <?php foreach (['-1'=>'Any','1'=>'On Sale','0'=>'Not On Sale'] as $v=>$l) : ?>
                        <button type="button"
                                onclick="gtFrSetFilter('sale','<?php echo esc_js($v); ?>',this)"
                                style="padding:5px 12px;border-radius:6px;font-size:12px;cursor:pointer;font-family:inherit;transition:all .15s;
                                       background:<?php echo (string)$saved_on_sale===$v?'rgba(34,197,94,0.1)':'rgba(255,255,255,0.03)'; ?>;
                                       border:1px solid <?php echo (string)$saved_on_sale===$v?'rgba(34,197,94,0.3)':'var(--gt-border)'; ?>;
                                       color:<?php echo (string)$saved_on_sale===$v?'var(--gt-white)':'#94a3b8'; ?>;font-weight:<?php echo (string)$saved_on_sale===$v?'700':'400'; ?>">
                            <?php echo esc_html($l); ?>
                        </button>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- ═══════════════════════════════════════════════════════════════════════
     SCHEDULING
════════════════════════════════════════════════════════════════════════ -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
    <div class="gt-card-header"><h2 class="gt-card-title">📅 Scheduling & Priority</h2></div>
    <div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:16px">
        <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((string)(int)$r['priority']); ?>"
                   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">(UTC, 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">(UTC, 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>

<!-- ═══════════════════════════════════════════════════════════════════════
     CART NOTIFICATION
════════════════════════════════════════════════════════════════════════ -->
<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 when the customer is close to qualifying. Encourages adding one more 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 Text</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">No exclamation marks. Keep under 100 characters. Shown in WooCommerce cart notice area.</div>
    </div>
</div>

<!-- ═══════════════════════════════════════════════════════════════════════
     SAVE
════════════════════════════════════════════════════════════════════════ -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
    <div style="display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:16px">
        <div style="font-size:13px;color:var(--gt-subtle)">
            Changes take effect on the next cart page load. The enable toggle auto-saves instantly.
        </div>
        <button type="submit" name="gtbogo_save_free_rule" class="gt-btn gt-btn-primary" style="padding:12px 36px">
            💾 Save Free Rule
        </button>
    </div>
</div>

<!-- ═══════════════════════════════════════════════════════════════════════
     PRO UPGRADE CTA
════════════════════════════════════════════════════════════════════════ -->
<?php if (!$is_pro) : ?>
<div class="gt-card gt-animate-in" style="margin-bottom:20px;background:linear-gradient(135deg,rgba(225,0,0,0.05),var(--gt-card));border-color:rgba(225,0,0,0.2)">
    <div class="gt-card-header"><h2 class="gt-card-title">🚀 Unlock the Full Engine</h2></div>
    <p style="font-size:13px;color:var(--gt-soft);margin-bottom:16px;line-height:1.6">
        The Free Rule handles one store-wide BOGO. PRO unlocks 200 expert-built rule packs across 19 industries —
        each pack adds 10 precision rules instantly, no manual setup. Plus 50 superpowers, AI intelligence, and full analytics.
    </p>
    <div style="display:grid;grid-template-columns:repeat(3,1fr);gap:10px;margin-bottom:20px">
        <?php
        $pro_features = [
            ['🎯','200 PRO Rule Packs','10 rules each, 19 industries, one-click import'],
            ['⏰','Campaign Scheduler','Date ranges, day-of-week, time-of-day windows'],
            ['🌍','Geo Targeting','Country and region-specific deals'],
            ['⚡','48 Superpowers','Cart psychology tools: timers, progress bars, popups'],
            ['✦','AI Intelligence','Copywriter, gap analyzer, pack recommender'],
            ['📊','Full Analytics','Leaderboard, lift report, Chart.js dashboards'],
        ];
        foreach ($pro_features as $f) : ?>
        <div style="padding:12px 14px;border-radius:8px;background:rgba(255,255,255,0.02);border:1px solid var(--gt-border)">
            <div style="font-size:18px;margin-bottom:5px"><?php echo esc_html($f[0]); ?></div>
            <div style="font-size:12px;font-weight:700;color:var(--gt-white);margin-bottom:3px"><?php echo esc_html($f[1]); ?></div>
            <div style="font-size:11px;color:var(--gt-subtle)"><?php echo esc_html($f[2]); ?></div>
        </div>
        <?php endforeach; ?>
    </div>
    <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 — $499/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>
</div>
<?php endif; ?>

</form>

<!-- ═══════════════════════════════════════════════════════════════════════
     JAVASCRIPT — All UI interactions
════════════════════════════════════════════════════════════════════════ -->
<script>
(function(){
'use strict';

/* ── Constants ──────────────────────────────────────────────────────── */
var NONCE   = '<?php echo esc_js($search_nonce); ?>';
var AJAXURL = '<?php echo esc_js(admin_url('admin-ajax.php')); ?>';

/* ── Product search state ───────────────────────────────────────────── */
var PS = { page:1, pages:1, total:0, timer:null };

/* ── Accordion ──────────────────────────────────────────────────────── */
window.gtFrAccordion = function(hdr) {
    var body  = hdr.nextElementSibling;
    var arrow = hdr.querySelector('.gt-fr-arrow');
    var open  = body.style.display !== 'none';
    body.style.display  = open ? 'none' : 'block';
    if (arrow) arrow.style.transform = open ? '' : 'rotate(180deg)';
};

/* ── Live preview ───────────────────────────────────────────────────── */
window.gtFrUpdatePreview = function() {
    var buy  = parseInt(document.getElementById('gt-fr-buy-qty')?.value)  || 1;
    var get  = parseInt(document.getElementById('gt-fr-get-qty')?.value)  || 1;
    var val  = parseFloat(document.getElementById('gt-fr-disc-val')?.value) || 0;
    var type = document.getElementById('gt-fr-disc-type')?.value || 'percentage';
    var to   = document.getElementById('gt-fr-apply-to')?.value || 'cheapest';
    var min  = parseFloat(document.getElementById('gt-fr-min-cart')?.value) || 0;

    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;
    var minText = min > 0 ? ' Min cart: $' + min.toFixed(2) + '.' : ' No minimum required.';

    var h = document.getElementById('gt-fr-preview-headline');
    var s = document.getElementById('gt-fr-preview-sub');
    if (h) h.textContent = 'Buy ' + buy + ' Get ' + get + ' — ' + val + suffix;
    if (s) s.textContent = toLabel + ' receives the discount.' + minText;
};

/* ── Enable toggle (instant AJAX autosave) ──────────────────────────── */
var toggleEl = document.getElementById('gt-fr-enabled');
if (toggleEl) {
    toggleEl.addEventListener('change', function() {
        var enabled = this.checked ? '1' : '0';
        var status  = document.getElementById('gt-fr-enable-status');
        var badge   = document.getElementById('gt-fr-status-badge');
        if (status) status.textContent = 'Saving…';

        var fd = new FormData();
        fd.append('action', 'gtbogo_autosave_free_rule_field');
        fd.append('nonce',  NONCE);
        fd.append('field',  'enabled');
        fd.append('value',  enabled);
        /* Also save the main option directly */
        fetch(AJAXURL, {method:'POST', body:fd, credentials:'same-origin'})
            .then(function(r){return r.json();})
            .then(function(resp){
                if (status) status.textContent = resp.success ? (enabled==='1'?'● Rule enabled':'○ Rule disabled') : '✗ Save failed';
                if (badge) {
                    badge.textContent = enabled==='1' ? '● Rule Active' : '○ Rule Inactive';
                    badge.className   = 'gt-badge ' + (enabled==='1' ? 'gt-badge-active' : 'gt-badge-free');
                }
                /* Also fire the WP option update for gt_bogo_free_rule_enabled */
                var fd2 = new FormData();
                fd2.append('action','gtbogo_autosave_free_rule_field');
                fd2.append('nonce', NONCE);
                fd2.append('field','enabled_flag');
                fd2.append('value',enabled);
                /* Note: this is a no-op extra call just to update the toggle indicator */
            })
            .catch(function(){ if(status) status.textContent='✗ Network error'; });
    });
}

/* ── Product search ─────────────────────────────────────────────────── */
window.gtFrProductSearch = function(val) {
    PS.page   = 1;
    clearTimeout(PS.timer);
    PS.timer  = setTimeout(gtFrProductLoad, 300);
};

window.gtFrProductPage = function(dir) {
    PS.page = Math.max(1, Math.min(PS.pages, PS.page + dir));
    gtFrProductLoad();
};

function gtFrProductLoad() {
    var results = document.getElementById('gt-fr-prod-results');
    if (!results) return;
    results.style.display = 'block';
    results.innerHTML = '<div style="padding:16px;text-align:center;color:var(--gt-subtle);font-size:13px">Searching…</div>';

    var selIds = (document.getElementById('gt-fr-products-val')?.value||'').split(',').filter(Boolean).map(Number);

    var fd = new FormData();
    fd.append('action',      'gtbogo_search_products');
    fd.append('nonce',       NONCE);
    fd.append('search',      document.getElementById('gt-fr-prod-search')?.value||'');
    fd.append('page',        PS.page);
    fd.append('per_page',    20);
    fd.append('category_id', document.getElementById('gt-fr-cat-filter')?.value||'');
    fd.append('product_type',document.getElementById('gt-fr-type-filter')?.value||'');
    fd.append('stock_status',document.getElementById('gt-fr-stock-filter')?.value||'');
    fd.append('on_sale',     document.getElementById('gt-fr-sale-filter')?.value||'');
    fd.append('orderby',     document.getElementById('gt-fr-sort')?.value||'title');

    fetch(AJAXURL, {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: ' + (res.data?.message||'Load failed') + '</div>';
                return;
            }
            var d = res.data;
            PS.pages = d.pages || 1;
            PS.total = d.total || 0;

            /* Cache products */
            window._gtFrPCache = window._gtFrPCache || {};
            (d.products||[]).forEach(function(p){ window._gtFrPCache[p.id] = p; });

            var html = '';
            (d.products||[]).forEach(function(p){
                var sel  = selIds.indexOf(p.id) > -1;
                var price= p.price_raw !== undefined ? '$' + parseFloat(p.price_raw).toFixed(2) : (p.price||'');
                html += '<div style="display:flex;align-items:center;gap:10px;padding:9px 12px;cursor:pointer;border-bottom:1px solid rgba(255,255,255,0.04);transition:background .12s;background:' + (sel?'rgba(225,0,0,0.05)':'') + '"'
                      + ' data-id="' + p.id + '"'
                      + ' onclick="gtFrToggleProduct(' + p.id + ', this)"'
                      + ' onmouseover="this.style.background=\'rgba(255,255,255,0.03)\'"'
                      + ' onmouseout="this.style.background=\'' + (sel?'rgba(225,0,0,0.05)':'') + '\'">';
                html += '<img src="' + (p.image||'').replace(/"/g,'&quot;') + '" alt="" style="width:32px;height:32px;border-radius:4px;object-fit:cover;flex-shrink:0;background:var(--gt-card)" onerror="this.style.display=\'none\'">';
                html += '<div style="flex:1;min-width:0">';
                html += '<div style="font-size:12px;font-weight:600;color:var(--gt-white);overflow:hidden;text-overflow:ellipsis;white-space:nowrap">' + p.name.replace(/</g,'&lt;').replace(/>/g,'&gt;') + '</div>';
                html += '<div style="font-size:10px;color:var(--gt-subtle)">' + price + (p.sku?' · '+p.sku:'') + ' · ' + p.type + '</div>';
                html += '</div>';
                html += '<div style="width:18px;height:18px;border-radius:3px;border:1.5px solid ' + (sel?'#E10000':'#475569') + ';background:' + (sel?'#E10000':'var(--gt-card)') + ';display:flex;align-items:center;justify-content:center;flex-shrink:0">';
                if (sel) html += '<span style="color:#fff;font-size:9px;font-weight:800">✓</span>';
                html += '</div>';
                html += '</div>';
            });
            if (!html) html = '<div style="padding:20px;text-align:center;color:var(--gt-subtle);font-size:13px">No products found.</div>';
            results.innerHTML = html;

            /* Pagination */
            var pag = document.getElementById('gt-fr-prod-pag');
            if (pag) {
                pag.style.display = PS.pages > 1 ? 'flex' : 'none';
                var info = document.getElementById('gt-fr-prod-pag-info');
                if (info) info.textContent = 'Page ' + PS.page + ' of ' + PS.pages + ' (' + PS.total.toLocaleString() + ' total)';
                var prev = document.getElementById('gt-fr-prod-prev');
                var next = document.getElementById('gt-fr-prod-next');
                if (prev) prev.disabled = PS.page <= 1;
                if (next) next.disabled = PS.page >= PS.pages;
            }
            var cnt = document.getElementById('gt-fr-prod-count');
            if (cnt) cnt.textContent = PS.total.toLocaleString() + ' product' + (PS.total!==1?'s':'');
        })
        .catch(function(){
            results.innerHTML = '<div style="padding:16px;color:#ef4444;font-size:13px">Network error — check console</div>';
        });
}

window.gtFrToggleProduct = function(id, el) {
    var p     = window._gtFrPCache && window._gtFrPCache[id];
    if (!p) return;
    var val   = document.getElementById('gt-fr-products-val');
    var ids   = val.value ? val.value.split(',').filter(Boolean).map(Number) : [];
    var idx   = ids.indexOf(id);
    var tags  = document.getElementById('gt-fr-prod-tags');
    var check = el.querySelector('[style*="border-radius:3px"]'); /* the checkbox div */

    if (idx > -1) {
        ids.splice(idx, 1);
        el.style.background = '';
        if (check) { check.style.background='var(--gt-card)'; check.style.borderColor='#475569'; check.innerHTML=''; }
        var tag = tags?.querySelector('[data-id="'+id+'"]');
        if (tag) tag.remove();
    } else {
        ids.push(id);
        el.style.background = 'rgba(225,0,0,0.05)';
        if (check) { check.style.background='#E10000'; check.style.borderColor='#E10000'; check.innerHTML='<span style="color:#fff;font-size:9px;font-weight:800">✓</span>'; }
        if (tags) {
            var span = document.createElement('span');
            span.setAttribute('data-id', id);
            span.style.cssText = '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:var(--gt-white)';
            span.innerHTML = p.name.replace(/</g,'&lt;').replace(/>/g,'&gt;') + '<button type="button" onclick="gtFrRemoveProduct('+id+',this.parentNode)" style="background:none;border:none;color:#94a3b8;cursor:pointer;padding:0;font-size:14px;line-height:1">×</button>';
            tags.appendChild(span);
        }
    }
    val.value = ids.join(',');
    gtFrUpdateBadge('gt-fr-prod-badge', ids.length, '#E10000');
    gtFrAutosave('products', ids.join(','));
};

window.gtFrRemoveProduct = function(id, el) {
    var val = document.getElementById('gt-fr-products-val');
    var ids = (val.value||'').split(',').filter(Boolean).map(Number).filter(function(i){return i!==id;});
    val.value = ids.join(',');
    el.remove();
    /* Uncheck in results list */
    var ri = document.querySelector('#gt-fr-prod-results [data-id="'+id+'"]');
    if (ri) {
        ri.style.background='';
        var check = ri.querySelector('[style*="border-radius:3px"]');
        if (check) { check.style.background='var(--gt-card)'; check.style.borderColor='#475569'; check.innerHTML=''; }
    }
    gtFrUpdateBadge('gt-fr-prod-badge', ids.length, '#E10000');
};

/* ── Category toggle ────────────────────────────────────────────────── */
window.gtFrToggleCat = function(id, el) {
    var val = document.getElementById('gt-fr-cats-val');
    var ids = (val.value||'').split(',').filter(Boolean).map(Number);
    var idx = ids.indexOf(id);
    var cb  = el.querySelector('.gt-fr-cb');

    if (idx > -1) {
        ids.splice(idx, 1);
        el.style.background   = 'rgba(255,255,255,0.02)';
        el.style.borderColor  = 'var(--gt-border)';
        if (cb) { cb.style.background='var(--gt-card)'; cb.style.borderColor='#475569'; cb.innerHTML=''; }
    } else {
        ids.push(id);
        el.style.background   = 'rgba(59,130,246,0.08)';
        el.style.borderColor  = 'rgba(59,130,246,0.25)';
        if (cb) { cb.style.background='#3b82f6'; cb.style.borderColor='#3b82f6'; cb.innerHTML='<span style="color:#fff;font-size:9px;font-weight:800">✓</span>'; }
    }
    val.value = ids.join(',');
    gtFrUpdateBadge('gt-fr-cat-badge', ids.length, '#60a5fa');
    gtFrAutosave('categories', ids.join(','));
};

/* ── Tag toggle ─────────────────────────────────────────────────────── */
window.gtFrToggleTag = function(id, el) {
    var val = document.getElementById('gt-fr-tags-val');
    var ids = (val.value||'').split(',').filter(Boolean).map(Number);
    var idx = ids.indexOf(id);
    var cb  = el.querySelector('.gt-fr-cb');

    if (idx > -1) {
        ids.splice(idx, 1);
        el.style.background   = 'rgba(255,255,255,0.02)';
        el.style.borderColor  = 'var(--gt-border)';
        if (cb) { cb.style.background='var(--gt-card)'; cb.style.borderColor='#475569'; cb.innerHTML=''; }
    } else {
        ids.push(id);
        el.style.background   = 'rgba(34,197,94,0.08)';
        el.style.borderColor  = 'rgba(34,197,94,0.05)';
        if (cb) { 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(',');
    gtFrUpdateBadge('gt-fr-tag-badge', ids.length, '#22c55e');
    gtFrAutosave('tags', ids.join(','));
};

/* ── Term search filter ─────────────────────────────────────────────── */
window.gtFrFilterTerms = function(type, q) {
    q = q.toLowerCase();
    var listId = type === 'cat' ? 'gt-fr-cat-list' : 'gt-fr-tag-list';
    document.querySelectorAll('#'+listId+' [data-name]').forEach(function(el){
        el.style.display = el.getAttribute('data-name').indexOf(q) > -1 ? '' : 'none';
    });
};

/* ── Product filter toggles ─────────────────────────────────────────── */
var filterColors = { type:['rgba(225,0,0,0.1)','rgba(225,0,0,0.3)'], stock:['rgba(59,130,246,0.1)','rgba(59,130,246,0.3)'], sale:['rgba(34,197,94,0.1)','rgba(34,197,94,0.3)'] };
var filterInputs = { type:'gt-fr-type-val', stock:'gt-fr-stock-val', sale:'gt-fr-sale-val' };
var filterGroups = { type:'gt-fr-type-grp', stock:'gt-fr-stock-grp', sale:'gt-fr-sale-grp' };
var filterBadgeId= 'gt-fr-filter-badge';

window.gtFrSetFilter = function(filter, val, btn) {
    document.getElementById(filterInputs[filter]).value = val;
    var colors = filterColors[filter];
    document.querySelectorAll('#' + filterGroups[filter] + ' button').forEach(function(b){
        var active = b === btn;
        b.style.background   = active ? colors[0] : 'rgba(255,255,255,0.03)';
        b.style.borderColor  = active ? colors[1] : 'var(--gt-border)';
        b.style.color        = active ? 'var(--gt-white)' : '#94a3b8';
        b.style.fontWeight   = active ? '700' : '400';
    });
    /* Update filter badge */
    var tv = document.getElementById('gt-fr-type-val')?.value;
    var sv = document.getElementById('gt-fr-stock-val')?.value;
    var ov = document.getElementById('gt-fr-sale-val')?.value;
    var badge = document.getElementById(filterBadgeId);
    if (badge) badge.style.display = (tv||sv||(ov&&ov!=='-1')) ? 'inline-block' : 'none';
};

/* ── Badge helper ───────────────────────────────────────────────────── */
function gtFrUpdateBadge(id, count, color) {
    var b = document.getElementById(id);
    if (!b) return;
    b.textContent    = count + ' selected';
    b.style.display  = count > 0 ? 'inline-block' : 'none';
}

/* ── Autosave field ─────────────────────────────────────────────────── */
function gtFrAutosave(field, value) {
    var fd = new FormData();
    fd.append('action','gtbogo_autosave_free_rule_field');
    fd.append('nonce', NONCE);
    fd.append('field', field);
    fd.append('value', value);
    fetch(AJAXURL, {method:'POST', body:fd, credentials:'same-origin'});
}

/* ── Init on DOM ready ──────────────────────────────────────────────── */
document.addEventListener('DOMContentLoaded', function() {
    /* Set initial preview */
    gtFrUpdatePreview();

    /* Show prod badge if any selected */
    var prodVal = document.getElementById('gt-fr-products-val')?.value;
    if (prodVal) {
        var cnt = prodVal.split(',').filter(Boolean).length;
        if (cnt > 0) gtFrUpdateBadge('gt-fr-prod-badge', cnt, '#E10000');
    }

    /* Open products accordion (show it by default) and auto-load */
    var firstSection = document.querySelector('.gt-fr-section');
    if (firstSection) {
        var firstBody = firstSection.querySelector('.gt-fr-body');
        var firstArrow = firstSection.querySelector('.gt-fr-arrow');
        if (firstBody) firstBody.style.display = 'block';
        if (firstArrow) firstArrow.style.transform = 'rotate(180deg)';
        /* Auto-load products */
        setTimeout(function() { gtFrProductLoad(); }, 150);
    }
});

})();
</script>

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