<?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 — Deal Lockout Command Center
 *
 * Enterprise margin protection with:
 *   - Stacking protection (sale items, coupons, single-rule-per-product)
 *   - Discount caps with real-time margin impact calculator
 *   - Revenue Guard integration panel
 *   - Customer segment & archetype bypass rules
 *   - Schedule-based lockout (date ranges, days of week)
 *   - Category exclusions with AJAX live search
 *   - Quick preset buttons (Conservative / Moderate / Aggressive)
 *   - Lockout event log from audit log table
 *   - Rule conflict preview
 *   - Lockout test simulator
 *   - Per-archetype override toggles
 *   - Export / import lockout configuration as JSON
 *
 * @package GT_BOGO_Engine
 * @since   5.0.0
 */
if ( ! defined( 'ABSPATH' ) ) exit;
if ( ! current_user_can( 'manage_options' ) ) {
    wp_die( esc_html__( 'Insufficient permissions.', 'gt-bogo-engine' ) );
}

global $wpdb;

$is_pro  = function_exists( 'gt_bogo_has_pro' ) ? gt_bogo_has_pro() : false;
$nonce   = wp_create_nonce( 'gtbogo_deal_lockout' );
$message = '';
$msg_type = 'success';

/* ── Handle form save ─────────────────────────────────────────────────────── */
if ( $is_pro && isset( $_POST['gtbogo_save_lockout'] )
     && check_admin_referer( 'gtbogo_lockout', 'gtbogo_lo_nonce' ) ) {

    $lo = [
        'prevent_stack_on_sale'      => isset( $_POST['lo_prevent_sale'] ),
        'prevent_coupon_stack'       => isset( $_POST['lo_prevent_coupon'] ),
        'single_rule_per_product'    => isset( $_POST['lo_single_per_prod'] ),
        'block_on_wholesale'         => isset( $_POST['lo_block_wholesale'] ),
        'max_discount_pct'           => min( 100, absint( $_POST['lo_max_discount']    ?? 0 ) ),
        'min_margin_pct'             => min( 100, absint( $_POST['lo_min_margin']      ?? 0 ) ),
        'max_rules_per_cart'         => min( 20,  absint( $_POST['lo_max_cart_rules']  ?? 0 ) ),
        'max_discount_per_customer'  => absint( $_POST['lo_max_per_customer'] ?? 0 ),
        'floor_price_enabled'        => isset( $_POST['lo_floor_price'] ),
        'exclude_categories'         => array_map( 'absint', (array) ( $_POST['lo_exclude_cats'] ?? [] ) ),
        'archetype_bypasses'         => array_map( 'sanitize_key', (array) ( $_POST['lo_arch_bypass'] ?? [] ) ),
        'vip_bypass'                 => isset( $_POST['lo_vip_bypass'] ),
        'schedule_enabled'           => isset( $_POST['lo_schedule_enabled'] ),
        'schedule_start'             => sanitize_text_field( wp_unslash( $_POST['lo_schedule_start'] ?? '' ) ),
        'schedule_end'               => sanitize_text_field( wp_unslash( $_POST['lo_schedule_end']   ?? '' ) ),
        'schedule_days'              => array_map( 'absint', (array) ( $_POST['lo_schedule_days'] ?? [] ) ),
        'fallback_margin_pct'        => min( 100, absint( $_POST['lo_fallback_margin'] ?? 40 ) ),
    ];

    update_option( 'gtbogo_deal_lockout', $lo );

    // Sync fallback margin to Revenue Guard
    update_option( 'gtbogo_revenue_guard_fallback_margin', $lo['fallback_margin_pct'] );

    $message  = 'Deal lockout settings saved. All changes take effect immediately on the next cart load.';
    $msg_type = 'success';
}

/* ── Load current settings ────────────────────────────────────────────────── */
$lo = get_option( 'gtbogo_deal_lockout', [
    'prevent_stack_on_sale'     => false,
    'prevent_coupon_stack'      => false,
    'single_rule_per_product'   => false,
    'block_on_wholesale'        => false,
    'max_discount_pct'          => 0,
    'min_margin_pct'            => 0,
    'max_rules_per_cart'        => 0,
    'max_discount_per_customer' => 0,
    'floor_price_enabled'       => false,
    'exclude_categories'        => [],
    'archetype_bypasses'        => [],
    'vip_bypass'                => false,
    'schedule_enabled'          => false,
    'schedule_start'            => '',
    'schedule_end'              => '',
    'schedule_days'             => [],
    'fallback_margin_pct'       => 40,
] );

/* ── Category list for exclusions ────────────────────────────────────────── */
$all_cats = get_terms( [ 'taxonomy' => 'product_cat', 'hide_empty' => false, 'orderby' => 'count', 'order' => 'DESC', 'number' => 0 ] );
$excluded = array_map( 'intval', (array) ( $lo['exclude_categories'] ?? [] ) );

/* ── Revenue Guard status ────────────────────────────────────────────────── */
$rg_fallback = (int) get_option( 'gtbogo_revenue_guard_fallback_margin', 40 );
$rg_outcomes = 0;
$rg_protected = 0;
$outcomes_tbl = $wpdb->prefix . 'gtbogo_outcomes';
if ( $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $outcomes_tbl ) ) ) { // phpcs:ignore
    $rg_outcomes  = (int) $wpdb->get_var( $wpdb->prepare( // phpcs:ignore
        "SELECT COUNT(*) FROM {$outcomes_tbl} WHERE event_type = 'deal_rejected' AND reason LIKE %s
         AND fired_at > DATE_SUB(UTC_TIMESTAMP(), INTERVAL 30 DAY)",
        '%margin%'
    ) );
    $rg_protected = (float) $wpdb->get_var( $wpdb->prepare( // phpcs:ignore
        "SELECT SUM(deal_value) FROM {$outcomes_tbl} WHERE event_type = 'deal_rejected' AND reason LIKE %s
         AND fired_at > DATE_SUB(UTC_TIMESTAMP(), INTERVAL 30 DAY)",
        '%margin%'
    ) );
}

/* ── Recent lockout events from audit log ────────────────────────────────── */
$lockout_log = [];
$audit_tbl   = $wpdb->prefix . 'gtbogo_audit_log';
if ( $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $audit_tbl ) ) ) { // phpcs:ignore
    $lockout_log = $wpdb->get_results( // phpcs:ignore
        "SELECT action, object_type, object_id, message, user_id, created_at
         FROM {$audit_tbl}
         WHERE action LIKE '%lockout%' OR action LIKE '%margin%' OR action LIKE '%block%'
         ORDER BY created_at DESC LIMIT 25",
        ARRAY_A
    ) ?: [];
}

/* ── Active rules for conflict preview ───────────────────────────────────── */
$rules_tbl = $wpdb->prefix . 'gtbogo_rules';
$active_rules = [];
if ( $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $rules_tbl ) ) ) { // phpcs:ignore
    $active_rules = $wpdb->get_results( // phpcs:ignore
        "SELECT id, name, buy_type, get_type, buy_qty, get_qty, pack_id, pack_priority
         FROM {$rules_tbl} WHERE status = 'active' ORDER BY pack_priority DESC LIMIT 50",
        ARRAY_A
    ) ?: [];
}

/* ── Archetypes ───────────────────────────────────────────────────────────── */
$archetypes = [
    'platinum_returning' => 'Platinum Returning',
    'vip_active'         => 'VIP Active',
    'high_intent'        => 'High Intent',
    'gold_returning'     => 'Gold Returning',
    'at_risk'            => 'At Risk',
    'price_sensitive'    => 'Price Sensitive',
    'new_visitor'        => 'New Visitor',
    'universal'          => 'Universal',
];

$arch_bypasses = array_map( 'sanitize_key', (array) ( $lo['archetype_bypasses'] ?? [] ) );
$days_of_week  = [ 0 => 'Sun', 1 => 'Mon', 2 => 'Tue', 3 => 'Wed', 4 => 'Thu', 5 => 'Fri', 6 => 'Sat' ];
$sched_days    = array_map( 'intval', (array) ( $lo['schedule_days'] ?? [] ) );

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">🔒 Deal Lockout</h1>
        <p class="gt-page-subtitle">
            Margin protection engine — prevent runaway discounts, stacking conflicts,
            and enforce business rules across all BOGO activity.
        </p>
    </div>
    <div style="display:flex;gap:10px;flex-wrap:wrap">
        <button type="button" class="gt-btn gt-btn-ghost"
            onclick="gtLoExportConfig('<?php echo esc_js($nonce); ?>')">
            ↓ Export Config
        </button>
        <label class="gt-btn gt-btn-ghost" style="cursor:pointer;display:inline-flex;align-items:center;gap:6px">
            ↑ Import Config
            <input type="file" accept=".json" onchange="gtLoImportConfig(this,'<?php echo esc_js($nonce); ?>')" style="display:none">
        </label>
    </div>
</div>

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

<!-- ── Revenue Guard Status Banner ──────────────────────────────────── -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px;border-color:rgba(34,197,94,0.15)">
    <div style="display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:16px">
        <div style="display:flex;align-items:center;gap:16px">
            <div style="width:44px;height:44px;border-radius:10px;background:rgba(34,197,94,0.1);
                        display:flex;align-items:center;justify-content:center;font-size:22px;flex-shrink:0">
                🛡
            </div>
            <div>
                <div style="font-size:14px;font-weight:700;color:var(--gt-white);margin-bottom:2px">
                    Revenue Guard Active
                </div>
                <div style="font-size:12px;color:var(--gt-subtle)">
                    Margin floor: <strong style="color:#22c55e"><?php echo esc_html($rg_fallback); ?>%</strong>
                    &nbsp;·&nbsp;
                    <?php echo esc_html(number_format($rg_outcomes)); ?> deals blocked in last 30 days
                    &nbsp;·&nbsp;
                    $<?php echo esc_html(number_format((float)$rg_protected, 0)); ?> discount volume protected
                </div>
            </div>
        </div>
        <!-- Quick Presets -->
        <div style="display:flex;gap:8px;flex-wrap:wrap">
            <span style="font-size:11px;color:var(--gt-subtle);font-weight:700;align-self:center">Quick Presets:</span>
            <button type="button" class="gt-btn gt-btn-ghost gt-btn-sm"
                onclick="gtLoApplyPreset('conservative')" style="border-color:rgba(34,197,94,0.3);color:#22c55e">
                Conservative
            </button>
            <button type="button" class="gt-btn gt-btn-ghost gt-btn-sm"
                onclick="gtLoApplyPreset('moderate')" style="border-color:rgba(245,158,11,0.3);color:#f59e0b">
                Moderate
            </button>
            <button type="button" class="gt-btn gt-btn-ghost gt-btn-sm"
                onclick="gtLoApplyPreset('aggressive')" style="border-color:rgba(239,68,68,0.3);color:#ef4444">
                Aggressive
            </button>
        </div>
    </div>
</div>

<?php if ( ! $is_pro ) : ?>
<div class="gt-pro-gate gt-animate-in">
    <span class="gt-pro-gate-icon">🔒</span>
    <h2>PRO License Required</h2>
    <p>Deal Lockout prevents simultaneous promotions from eroding your margins — critical for luxury and fashion brands.</p>
    <a href="https://graphictshirts.shop/bogo/" target="_blank" rel="noopener" class="gt-btn gt-btn-primary">
        Purchase PRO
    </a>
</div>
<?php else : ?>

<form method="post" action="" id="gt-lo-form">
<?php wp_nonce_field( 'gtbogo_lockout', 'gtbogo_lo_nonce' ); ?>

<!-- ═══════════════════════════════════════════════════════════════════════════
     STACKING PROTECTION
════════════════════════════════════════════════════════════════════════════ -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
    <div class="gt-card-header">
        <h2 class="gt-card-title">🛡 Stacking Protection</h2>
        <span style="font-size:12px;color:var(--gt-subtle)">Control what can combine with BOGO rules</span>
    </div>

    <?php
    $stacking_options = [
        [ 'lo_prevent_sale',    'prevent_stack_on_sale',   'Block BOGO on Sale Items',
          'BOGO rules will not apply to products already marked as on-sale. Prevents compounding sale + BOGO discounts that erode margin.',
          'critical' ],
        [ 'lo_prevent_coupon',  'prevent_coupon_stack',    'Block BOGO + Coupon Stacking',
          'Prevents customers from combining BOGO rules with WooCommerce coupon codes simultaneously.',
          'high' ],
        [ 'lo_single_per_prod', 'single_rule_per_product', 'One Rule Per Product Maximum',
          'Only the highest-priority matching rule fires per product. Prevents the same item receiving multiple stacked discounts.',
          'high' ],
        [ 'lo_block_wholesale', 'block_on_wholesale',      'Block BOGO for Wholesale Customers',
          'B2B / wholesale accounts (managed by GT_BOGO_B2B_Pricing) already have volume pricing — BOGO does not apply.',
          'medium' ],
        [ 'lo_vip_bypass',      'vip_bypass',              'VIP Customers Bypass All Lockout Rules',
          'Platinum and Elite tier customers are exempt from all lockout restrictions. Loyalty reward above all else.',
          'low' ],
    ];
    foreach ( $stacking_options as $opt ) :
        $impact_colors = [ 'critical'=>'#ef4444','high'=>'#f59e0b','medium'=>'#3b82f6','low'=>'#22c55e' ];
    ?>
    <div class="gt-setting-row">
        <div>
            <div class="gt-setting-label">
                <?php echo esc_html($opt[2]); ?>
                <span style="margin-left:8px;padding:1px 7px;border-radius:20px;font-size:9px;font-weight:800;
                             background:<?php echo esc_attr($impact_colors[$opt[4]]); ?>15;
                             color:<?php echo esc_attr($impact_colors[$opt[4]]); ?>;
                             text-transform:uppercase;letter-spacing:.06em">
                    <?php echo esc_html(strtoupper($opt[4])); ?> impact
                </span>
            </div>
            <div class="gt-setting-desc"><?php echo esc_html($opt[3]); ?></div>
        </div>
        <label class="gt-toggle">
            <input type="checkbox" name="<?php echo esc_attr($opt[0]); ?>" value="1"
                   id="gt-lo-<?php echo esc_attr($opt[0]); ?>"
                   <?php checked( ! empty( $lo[ $opt[1] ] ) ); ?>>
            <span class="gt-toggle-track"><span class="gt-toggle-thumb"></span></span>
        </label>
    </div>
    <?php endforeach; ?>
</div>

<!-- ═══════════════════════════════════════════════════════════════════════════
     DISCOUNT CAPS + REAL-TIME MARGIN CALCULATOR
════════════════════════════════════════════════════════════════════════════ -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
    <div class="gt-card-header">
        <h2 class="gt-card-title">📊 Discount Caps & Margin Protection</h2>
        <span style="font-size:12px;color:var(--gt-subtle)">Set to 0 to disable each cap</span>
    </div>

    <div style="display:grid;grid-template-columns:1fr 1fr;gap:16px;margin-bottom:20px">
        <div class="gt-form-group" style="margin:0">
            <label class="gt-form-label" for="gt-lo-max-disc">Maximum Total Discount (%)</label>
            <input type="number" name="lo_max_discount" id="gt-lo-max-disc" class="gt-input"
                   min="0" max="100" step="1"
                   value="<?php echo esc_attr((string)($lo['max_discount_pct']??0)); ?>"
                   oninput="gtLoUpdateCalc()">
            <div class="gt-form-hint">Cart discount will never exceed this % of cart subtotal (0 = no cap)</div>
        </div>
        <div class="gt-form-group" style="margin:0">
            <label class="gt-form-label" for="gt-lo-min-margin">Minimum Margin Floor (%)</label>
            <input type="number" name="lo_min_margin" id="gt-lo-min-margin" class="gt-input"
                   min="0" max="100" step="1"
                   value="<?php echo esc_attr((string)($lo['min_margin_pct']??0)); ?>"
                   oninput="gtLoUpdateCalc()">
            <div class="gt-form-hint">Rule won't fire if margin drops below this %. Uses cost price meta or <?php echo esc_html($rg_fallback); ?>% fallback.</div>
        </div>
        <div class="gt-form-group" style="margin:0">
            <label class="gt-form-label" for="gt-lo-max-rules">Maximum Rules Per Cart</label>
            <input type="number" name="lo_max_cart_rules" id="gt-lo-max-rules" class="gt-input"
                   min="0" max="20" step="1"
                   value="<?php echo esc_attr((string)($lo['max_rules_per_cart']??0)); ?>">
            <div class="gt-form-hint">Maximum simultaneous BOGO rules on a single cart (0 = no limit)</div>
        </div>
        <div class="gt-form-group" style="margin:0">
            <label class="gt-form-label" for="gt-lo-max-cust">Max Discount Per Customer (per day, $)</label>
            <input type="number" name="lo_max_per_customer" id="gt-lo-max-cust" class="gt-input"
                   min="0" step="1"
                   value="<?php echo esc_attr((string)($lo['max_discount_per_customer']??0)); ?>">
            <div class="gt-form-hint">A customer cannot receive more than this total BOGO discount per day (0 = unlimited)</div>
        </div>
        <div class="gt-form-group" style="margin:0">
            <label class="gt-form-label" for="gt-lo-fallback">Fallback Margin Assumption (%)</label>
            <input type="number" name="lo_fallback_margin" id="gt-lo-fallback" class="gt-input"
                   min="0" max="100" step="1"
                   value="<?php echo esc_attr((string)($lo['fallback_margin_pct']??40)); ?>"
                   oninput="gtLoUpdateCalc()">
            <div class="gt-form-hint">Assumed margin % when no cost price is set on a product. Synced to Revenue Guard.</div>
        </div>
        <div class="gt-form-group" style="margin:0">
            <label class="gt-setting-label">Enable Floor Price Protection</label>
            <div class="gt-setting-desc">Never allow discount to take product price below cost price meta field.</div>
            <label class="gt-toggle" style="margin-top:8px">
                <input type="checkbox" name="lo_floor_price" value="1"
                       <?php checked( ! empty( $lo['floor_price_enabled'] ) ); ?>>
                <span class="gt-toggle-track"><span class="gt-toggle-thumb"></span></span>
            </label>
        </div>
    </div>

    <!-- Real-time Margin Impact Calculator -->
    <div style="background:rgba(255,255,255,0.02);border:1px solid var(--gt-border);border-radius:10px;padding:18px">
        <div style="font-size:12px;font-weight:700;color:var(--gt-white);margin-bottom:12px">
            🧮 Real-Time Margin Impact Calculator
        </div>
        <div style="display:flex;align-items:center;gap:12px;flex-wrap:wrap;margin-bottom:14px">
            <div>
                <label style="font-size:11px;color:var(--gt-subtle);display:block;margin-bottom:4px">Cart Subtotal ($)</label>
                <input type="number" id="gt-lo-calc-cart" value="150" min="0" step="10"
                       oninput="gtLoUpdateCalc()"
                       style="padding:7px 10px;background:var(--gt-card);border:1px solid var(--gt-border-md);
                              border-radius:6px;color:var(--gt-white);font-size:13px;width:110px;font-family:inherit">
            </div>
            <div>
                <label style="font-size:11px;color:var(--gt-subtle);display:block;margin-bottom:4px">Proposed Discount ($)</label>
                <input type="number" id="gt-lo-calc-disc" value="30" min="0" step="5"
                       oninput="gtLoUpdateCalc()"
                       style="padding:7px 10px;background:var(--gt-card);border:1px solid var(--gt-border-md);
                              border-radius:6px;color:var(--gt-white);font-size:13px;width:110px;font-family:inherit">
            </div>
        </div>
        <div style="display:grid;grid-template-columns:repeat(4,1fr);gap:10px" id="gt-lo-calc-results">
            <?php
            $calc_items = [
                ['id'=>'gt-lo-cr-disc-pct', 'label'=>'Discount %',    'color'=>'#f59e0b'],
                ['id'=>'gt-lo-cr-margin',   'label'=>'Effective Margin','color'=>'#22c55e'],
                ['id'=>'gt-lo-cr-cap',      'label'=>'Cap Triggered?', 'color'=>'var(--gt-white)'],
                ['id'=>'gt-lo-cr-block',    'label'=>'Rule Fires?',    'color'=>'var(--gt-white)'],
            ];
            foreach ($calc_items as $ci) : ?>
            <div style="text-align:center;padding:10px;background:var(--gt-card);border-radius:7px;border:1px solid var(--gt-border)">
                <div style="font-size:16px;font-weight:800;color:<?php echo esc_attr($ci['color']); ?>"
                     id="<?php echo esc_attr($ci['id']); ?>">—</div>
                <div style="font-size:10px;color:var(--gt-subtle);font-weight:600;text-transform:uppercase;letter-spacing:.06em;margin-top:3px">
                    <?php echo esc_html($ci['label']); ?>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>
</div>

<!-- ═══════════════════════════════════════════════════════════════════════════
     ARCHETYPE BYPASS RULES
════════════════════════════════════════════════════════════════════════════ -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
    <div class="gt-card-header">
        <h2 class="gt-card-title">🧠 Archetype Bypass Rules</h2>
        <span style="font-size:12px;color:var(--gt-subtle)">Selected archetypes ignore all lockout restrictions</span>
    </div>
    <div style="margin-bottom:12px;font-size:12px;color:var(--gt-subtle);line-height:1.5">
        Archetypes checked here will bypass stacking protection, discount caps, and schedule lockouts.
        Use for your highest-value customer segments to ensure they always receive the best available deal.
    </div>
    <div style="display:grid;grid-template-columns:repeat(4,1fr);gap:8px">
    <?php foreach ( $archetypes as $arch_key => $arch_label ) :
        $arch_checked = in_array( $arch_key, $arch_bypasses, true );
        $arch_is_top  = in_array( $arch_key, ['platinum_returning','vip_active'], true );
    ?>
    <label style="display:flex;align-items:center;gap:8px;padding:10px 12px;
                  background:<?php echo $arch_checked?'rgba(225,0,0,0.07)':'rgba(255,255,255,0.02)'; ?>;
                  border:1px solid <?php echo $arch_checked?'rgba(225,0,0,0.25)':'var(--gt-border)'; ?>;
                  border-radius:7px;cursor:pointer;transition:all .15s">
        <input type="checkbox" name="lo_arch_bypass[]" value="<?php echo esc_attr($arch_key); ?>"
               <?php checked($arch_checked); ?>
               style="accent-color:var(--gt-red);width:14px;height:14px">
        <div>
            <div style="font-size:12px;font-weight:700;color:<?php echo $arch_is_top?'#f59e0b':'var(--gt-white)'; ?>">
                <?php echo esc_html($arch_label); ?>
            </div>
            <?php if ($arch_is_top) : ?>
            <div style="font-size:10px;color:var(--gt-subtle)">Recommended bypass</div>
            <?php endif; ?>
        </div>
    </label>
    <?php endforeach; ?>
    </div>
</div>

<!-- ═══════════════════════════════════════════════════════════════════════════
     SCHEDULE-BASED LOCKOUT
════════════════════════════════════════════════════════════════════════════ -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
    <div class="gt-card-header">
        <h2 class="gt-card-title">📅 Schedule-Based Lockout</h2>
        <span style="font-size:12px;color:var(--gt-subtle)">Disable all BOGO during specific windows (e.g. Black Friday, flash sales)</span>
    </div>

    <div class="gt-setting-row" style="margin-bottom:16px">
        <div>
            <div class="gt-setting-label">Enable Schedule Lockout</div>
            <div class="gt-setting-desc">When active, all BOGO rules are suspended during the configured window regardless of other settings.</div>
        </div>
        <label class="gt-toggle">
            <input type="checkbox" name="lo_schedule_enabled" value="1" id="gt-lo-sched-toggle"
                   onchange="gtLoToggleSchedule()"
                   <?php checked( ! empty( $lo['schedule_enabled'] ) ); ?>>
            <span class="gt-toggle-track"><span class="gt-toggle-thumb"></span></span>
        </label>
    </div>

    <div id="gt-lo-sched-config" style="<?php echo empty($lo['schedule_enabled'])?'opacity:.4;pointer-events:none':''; ?>">
        <div style="display:grid;grid-template-columns:1fr 1fr;gap:16px;margin-bottom:16px">
            <div class="gt-form-group" style="margin:0">
                <label class="gt-form-label">Lockout Start (UTC)</label>
                <input type="datetime-local" name="lo_schedule_start" class="gt-input"
                       value="<?php echo esc_attr($lo['schedule_start']??''); ?>">
                <div class="gt-form-hint">All times are UTC. Leave blank for no start restriction.</div>
            </div>
            <div class="gt-form-group" style="margin:0">
                <label class="gt-form-label">Lockout End (UTC)</label>
                <input type="datetime-local" name="lo_schedule_end" class="gt-input"
                       value="<?php echo esc_attr($lo['schedule_end']??''); ?>">
                <div class="gt-form-hint">Rules re-activate automatically after this time.</div>
            </div>
        </div>
        <div>
            <label class="gt-form-label" style="margin-bottom:8px">Recurring Days of Week (lock every week on these days)</label>
            <div style="display:flex;gap:8px;flex-wrap:wrap">
            <?php foreach ($days_of_week as $dow_num => $dow_label) : ?>
            <label style="display:flex;align-items:center;gap:5px;padding:6px 12px;
                          background:<?php echo in_array($dow_num,$sched_days,true)?'rgba(225,0,0,0.1)':'rgba(255,255,255,0.03)'; ?>;
                          border:1px solid <?php echo in_array($dow_num,$sched_days,true)?'rgba(225,0,0,0.3)':'var(--gt-border)'; ?>;
                          border-radius:6px;cursor:pointer;transition:all .15s;font-size:12px;font-weight:600;color:var(--gt-white)">
                <input type="checkbox" name="lo_schedule_days[]" value="<?php echo esc_attr((string)$dow_num); ?>"
                       <?php checked(in_array($dow_num,$sched_days,true)); ?>
                       style="accent-color:var(--gt-red)">
                <?php echo esc_html($dow_label); ?>
            </label>
            <?php endforeach; ?>
            </div>
        </div>
    </div>
</div>

<!-- ═══════════════════════════════════════════════════════════════════════════
     CATEGORY EXCLUSIONS
════════════════════════════════════════════════════════════════════════════ -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
    <div class="gt-card-header">
        <h2 class="gt-card-title">🚫 Excluded Categories</h2>
        <span style="font-size:12px;color:var(--gt-subtle)">
            BOGO rules never apply to products in these categories
            <?php if (!empty($excluded)): ?> · <strong style="color:var(--gt-red)"><?php echo count($excluded); ?> excluded</strong><?php endif; ?>
        </span>
    </div>

    <!-- Live category search -->
    <div style="margin-bottom:14px">
        <input type="text" id="gt-lo-cat-search" placeholder="Search categories…"
               oninput="gtLoFilterCats()"
               style="padding:8px 12px;background:var(--gt-card);border:1px solid var(--gt-border-md);
                      border-radius:6px;color:var(--gt-white);font-size:13px;width:100%;
                      box-sizing:border-box;font-family:inherit">
    </div>

    <div id="gt-lo-cat-grid" style="display:grid;grid-template-columns:repeat(auto-fill,minmax(200px,1fr));gap:6px;max-height:320px;overflow-y:auto">
    <?php if ( ! is_wp_error($all_cats) ) : foreach ( (array)$all_cats as $cat ) :
        $is_excl = in_array( (int)$cat->term_id, $excluded, true );
    ?>
    <label class="gt-lo-cat-chip"
           data-name="<?php echo esc_attr(strtolower($cat->name)); ?>"
           style="display:flex;align-items:center;gap:8px;padding:8px 10px;
                  background:<?php echo $is_excl?'rgba(239,68,68,0.07)':'rgba(255,255,255,0.02)'; ?>;
                  border:1px solid <?php echo $is_excl?'rgba(239,68,68,0.25)':'var(--gt-border)'; ?>;
                  border-radius:7px;cursor:pointer;transition:all .15s">
        <input type="checkbox" name="lo_exclude_cats[]"
               value="<?php echo esc_attr((string)(int)$cat->term_id); ?>"
               <?php checked($is_excl); ?>
               style="accent-color:#ef4444;width:13px;height:13px;flex-shrink:0">
        <div style="min-width:0">
            <div style="font-size:12px;font-weight:600;color:var(--gt-white);overflow:hidden;text-overflow:ellipsis;white-space:nowrap">
                <?php echo esc_html($cat->name); ?>
            </div>
            <div style="font-size:10px;color:var(--gt-subtle)"><?php echo esc_html((string)$cat->count); ?> products</div>
        </div>
    </label>
    <?php endforeach; endif; ?>
    </div>
</div>

<!-- ═══════════════════════════════════════════════════════════════════════════
     RULE CONFLICT PREVIEW
════════════════════════════════════════════════════════════════════════════ -->
<?php if ( ! empty($active_rules) ) : ?>
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
    <div class="gt-card-header">
        <h2 class="gt-card-title">⚡ Active Rules Conflict Preview</h2>
        <span style="font-size:12px;color:var(--gt-subtle)"><?php echo count($active_rules); ?> active rules — potential stacking conflicts</span>
    </div>
    <div style="overflow-x:auto">
        <table style="width:100%;border-collapse:collapse;font-size:12px">
            <thead>
                <tr style="border-bottom:1px solid var(--gt-border)">
                    <?php foreach (['Rule Name','Type','Pack Priority','Stack Risk','Action'] as $col) : ?>
                    <th style="padding:9px 12px;text-align:left;font-size:10px;font-weight:800;
                               letter-spacing:.1em;text-transform:uppercase;color:var(--gt-subtle)">
                        <?php echo esc_html($col); ?>
                    </th>
                    <?php endforeach; ?>
                </tr>
            </thead>
            <tbody>
            <?php foreach ( $active_rules as $ar ) :
                $lo_max = (int)($lo['max_rules_per_cart']??0);
                $risk   = $lo_max > 0 && count($active_rules) > $lo_max ? 'high' : 'low';
                $rc     = $risk==='high'?'#ef4444':'#22c55e';
            ?>
            <tr style="border-bottom:1px solid rgba(255,255,255,0.03)">
                <td style="padding:8px 12px;font-weight:600;color:var(--gt-white)"><?php echo esc_html($ar['name']); ?></td>
                <td style="padding:8px 12px;color:var(--gt-subtle)">
                    Buy <?php echo esc_html($ar['buy_qty']); ?> / Get <?php echo esc_html($ar['get_qty']); ?>
                </td>
                <td style="padding:8px 12px;color:var(--gt-subtle)"><?php echo esc_html($ar['pack_priority']??'—'); ?></td>
                <td style="padding:8px 12px">
                    <span style="color:<?php echo esc_attr($rc); ?>;font-weight:700;font-size:11px">
                        <?php echo $risk==='high' ? '⚠ Stack Risk' : '✓ No Conflict'; ?>
                    </span>
                </td>
                <td style="padding:8px 12px">
                    <a href="<?php echo esc_url(admin_url('admin.php?page=gt-bogo-engine&tab=pro-rules&edit='.(int)$ar['id'])); ?>"
                       style="font-size:11px;color:var(--gt-red);text-decoration:none;font-weight:700">
                        Edit →
                    </a>
                </td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>
<?php endif; ?>

<!-- ═══════════════════════════════════════════════════════════════════════════
     LOCKOUT EVENT LOG
════════════════════════════════════════════════════════════════════════════ -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
    <div class="gt-card-header">
        <h2 class="gt-card-title">📋 Lockout Event Log</h2>
        <span style="font-size:12px;color:var(--gt-subtle)">Last 25 lockout and margin-block events from audit log</span>
    </div>
    <?php if ( empty($lockout_log) ) : ?>
    <div style="padding:24px;text-align:center;color:var(--gt-subtle);font-size:13px">
        No lockout events recorded yet. Events appear here when the lockout rules block a deal.
    </div>
    <?php else : ?>
    <div style="overflow-x:auto">
        <table style="width:100%;border-collapse:collapse;font-size:12px">
            <thead>
                <tr style="border-bottom:1px solid var(--gt-border)">
                    <?php foreach (['Time','Action','Object','Message'] as $col) : ?>
                    <th style="padding:9px 12px;text-align:left;font-size:10px;font-weight:800;
                               letter-spacing:.1em;text-transform:uppercase;color:var(--gt-subtle)">
                        <?php echo esc_html($col); ?>
                    </th>
                    <?php endforeach; ?>
                </tr>
            </thead>
            <tbody>
            <?php foreach ( $lockout_log as $le ) : ?>
            <tr style="border-bottom:1px solid rgba(255,255,255,0.03)">
                <td style="padding:8px 12px;color:var(--gt-subtle);white-space:nowrap;font-size:11px">
                    <?php echo esc_html( gmdate('M j H:i', strtotime($le['created_at'])) ); ?>
                </td>
                <td style="padding:8px 12px;font-family:'DM Mono','Courier New',monospace;font-size:10px;color:#f59e0b">
                    <?php echo esc_html($le['action']); ?>
                </td>
                <td style="padding:8px 12px;color:var(--gt-subtle)">
                    <?php echo esc_html($le['object_type'].'#'.$le['object_id']); ?>
                </td>
                <td style="padding:8px 12px;color:var(--gt-white);font-size:11px;max-width:400px">
                    <?php echo esc_html(mb_strimwidth($le['message']??'',0,100,'…')); ?>
                </td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php endif; ?>
</div>

<!-- ═══════════════════════════════════════════════════════════════════════════
     SAVE
════════════════════════════════════════════════════════════════════════════ -->
<div class="gt-card gt-animate-in">
    <div style="display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:16px">
        <div>
            <div style="font-size:13px;font-weight:600;color:var(--gt-white)">Save Lockout Configuration</div>
            <div style="font-size:12px;color:var(--gt-subtle);margin-top:2px">
                Lockout rules take priority over all PRO rules and packs. Changes apply on the next cart calculation.
            </div>
        </div>
        <div style="display:flex;gap:10px">
            <button type="button" class="gt-btn gt-btn-ghost"
                onclick="gtLoTestSimulate('<?php echo esc_js($nonce); ?>')">
                🔬 Test Lockout
            </button>
            <button type="submit" name="gtbogo_save_lockout" class="gt-btn gt-btn-primary"
                    style="padding:12px 32px">
                💾 Save Settings
            </button>
        </div>
    </div>
</div>

</form>
<?php endif; ?>

<!-- ── Test Result Panel ──────────────────────────────────────────────── -->
<div id="gt-lo-test-result" class="gt-card gt-animate-in" style="display:none;margin-top:16px;border-color:rgba(59,130,246,0.2)">
    <div class="gt-card-header"><h2 class="gt-card-title">🔬 Lockout Test Result</h2></div>
    <div id="gt-lo-test-content" style="font-size:13px;color:var(--gt-subtle);padding:4px 0"></div>
</div>

<!-- ═══════════════════════════════════════════════════════════════════════════
     JAVASCRIPT
════════════════════════════════════════════════════════════════════════════ -->
<script>
(function(){
'use strict';

/* ── Real-time margin calculator ─────────────────────────────────────── */
window.gtLoUpdateCalc = function() {
    var cart     = parseFloat(document.getElementById('gt-lo-calc-cart')?.value) || 0;
    var disc     = parseFloat(document.getElementById('gt-lo-calc-disc')?.value) || 0;
    var maxPct   = parseFloat(document.getElementById('gt-lo-max-disc')?.value)  || 0;
    var minMarg  = parseFloat(document.getElementById('gt-lo-min-margin')?.value)|| 0;
    var fallback = parseFloat(document.getElementById('gt-lo-fallback')?.value)  || 40;

    var discPct    = cart > 0 ? (disc / cart * 100).toFixed(1) : '0.0';
    var grossMargin = cart * (fallback / 100);
    var netMargin  = grossMargin - disc;
    var netPct     = cart > 0 ? (netMargin / cart * 100).toFixed(1) : '0.0';
    var capHit     = maxPct > 0 && discPct > maxPct;
    var margHit    = minMarg > 0 && netPct < minMarg;
    var fires      = !capHit && !margHit;

    function setEl(id, txt, color) {
        var el = document.getElementById(id);
        if (el) { el.textContent = txt; el.style.color = color; }
    }
    setEl('gt-lo-cr-disc-pct', discPct + '%',     discPct > 40 ? '#ef4444' : '#f59e0b');
    setEl('gt-lo-cr-margin',   netPct  + '%',     netPct >= minMarg || minMarg===0 ? '#22c55e' : '#ef4444');
    setEl('gt-lo-cr-cap',      capHit  ? '⚠ Cap Hit' : '✓ Within Cap', capHit ? '#ef4444' : '#22c55e');
    setEl('gt-lo-cr-block',    fires   ? '✓ Fires'   : '✗ Blocked',    fires  ? '#22c55e' : '#ef4444');
};

/* ── Schedule toggle ─────────────────────────────────────────────────── */
window.gtLoToggleSchedule = function() {
    var enabled = document.getElementById('gt-lo-sched-toggle')?.checked;
    var cfg     = document.getElementById('gt-lo-sched-config');
    if (cfg) { cfg.style.opacity = enabled ? '1' : '0.4'; cfg.style.pointerEvents = enabled ? '' : 'none'; }
};

/* ── Category search ─────────────────────────────────────────────────── */
window.gtLoFilterCats = function() {
    var q    = document.getElementById('gt-lo-cat-search')?.value.toLowerCase() || '';
    document.querySelectorAll('.gt-lo-cat-chip').forEach(function(chip) {
        var name = chip.getAttribute('data-name') || '';
        chip.style.display = name.includes(q) ? '' : 'none';
    });
};

/* ── Quick presets ───────────────────────────────────────────────────── */
var presets = {
    conservative: { max_discount: 25, min_margin: 35, max_rules: 1, prevent_sale: true,  prevent_coupon: true  },
    moderate:     { max_discount: 50, min_margin: 20, max_rules: 2, prevent_sale: true,  prevent_coupon: false },
    aggressive:   { max_discount: 70, min_margin: 10, max_rules: 5, prevent_sale: false, prevent_coupon: false },
};
window.gtLoApplyPreset = function(name) {
    var p = presets[name];
    if (!p) return;
    if (!confirm('Apply "' + name + '" preset? This will overwrite your current cap settings.')) return;
    var set = function(id, val) { var el = document.getElementById(id); if (el) el.value = val; };
    var chk = function(id, val) { var el = document.getElementById('gt-lo-' + id); if (el) el.checked = val; };
    set('gt-lo-max-disc',   p.max_discount);
    set('gt-lo-min-margin', p.min_margin);
    set('gt-lo-max-rules',  p.max_rules);
    chk('lo_prevent_sale',  p.prevent_sale);
    chk('lo_prevent_coupon', p.prevent_coupon);
    gtLoUpdateCalc();
};

/* ── Test Simulate ───────────────────────────────────────────────────── */
window.gtLoTestSimulate = function(nonce) {
    var panel   = document.getElementById('gt-lo-test-result');
    var content = document.getElementById('gt-lo-test-content');
    if (!panel || !content) return;
    panel.style.display = 'block';
    content.innerHTML   = '<div style="color:var(--gt-subtle)">Testing lockout rules against current cart session…</div>';
    panel.scrollIntoView({behavior:'smooth',block:'center'});

    var fd = new FormData();
    fd.append('action', 'gtbogo_lo_test_simulate');
    fd.append('nonce',  nonce);

    fetch(ajaxurl, {method:'POST',body:fd})
        .then(function(r){return r.json();})
        .then(function(resp){
            if (resp.success) {
                var d = resp.data;
                content.innerHTML =
                    '<div style="display:grid;grid-template-columns:1fr 1fr;gap:14px">' +
                    '<div><div style="font-size:11px;color:var(--gt-subtle);margin-bottom:4px">Cart Items</div>' +
                    '<div style="font-size:13px;color:var(--gt-white)">' + (d.cart_items || 'Cart empty') + '</div></div>' +
                    '<div><div style="font-size:11px;color:var(--gt-subtle);margin-bottom:4px">Lockout Result</div>' +
                    '<div style="font-size:14px;font-weight:700;color:' + (d.fires?'#22c55e':'#ef4444') + '">' +
                    (d.fires ? '✓ Rules would fire' : '✗ Blocked by lockout') + '</div>' +
                    '<div style="font-size:11px;color:var(--gt-subtle);margin-top:3px">' + (d.reason||'') + '</div></div></div>';
            } else {
                content.innerHTML = '<div style="color:#ef4444">' + (resp.data||'Test failed.') + '</div>';
            }
        })
        .catch(function(){
            content.innerHTML = '<div style="color:#ef4444">Network error during test.</div>';
        });
};

/* ── Export config JSON ──────────────────────────────────────────────── */
window.gtLoExportConfig = function(nonce) {
    window.open(ajaxurl + '?action=gtbogo_lo_export_config&nonce=' + encodeURIComponent(nonce), '_blank');
};

/* ── Import config JSON ──────────────────────────────────────────────── */
window.gtLoImportConfig = function(input, nonce) {
    var file = input.files[0];
    if (!file) return;
    var reader = new FileReader();
    reader.onload = function(e) {
        try {
            var cfg = JSON.parse(e.target.result);
            if (!cfg || typeof cfg !== 'object') throw new Error('Invalid JSON');
            var fd = new FormData();
            fd.append('action', 'gtbogo_lo_import_config');
            fd.append('nonce',  nonce);
            fd.append('config', JSON.stringify(cfg));
            fetch(ajaxurl,{method:'POST',body:fd})
                .then(function(r){return r.json();})
                .then(function(resp){ if(resp.success) location.reload(); else alert(resp.data||'Import failed.'); });
        } catch(err) { alert('Invalid JSON file: ' + err.message); }
    };
    reader.readAsText(file);
};

/* ── Init calculator on load ─────────────────────────────────────────── */
document.addEventListener('DOMContentLoaded', function() { gtLoUpdateCalc(); });

})();
</script>

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