<?php
// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals
// phpcs:disable WordPress.Security.NonceVerification
// phpcs:disable WordPress.Security.ValidatedSanitizedInput
// phpcs:disable WordPress.DB.PreparedSQL
// phpcs:disable WordPress.DB.DirectDatabaseQuery
// phpcs:disable WordPress.DB.SlowDBQuery
// phpcs:disable PluginCheck.Security.DirectDB
// phpcs:disable WordPressVIPMinimum
/**
 * GT BOGO Engine PRO — Rules Manager
 *
 * Two sections:
 *  1. Custom Inventory Rules — unlimited, fully editable, user-created per product/category/tag
 *  2. PRO Pack Rules — read-only (toggle only), imported from licensed packs
 *
 * @package GT_BOGO_Engine
 * @since   5.0.0
 */
if ( ! defined( 'ABSPATH' ) ) exit;
if ( ! current_user_can( 'manage_woocommerce' ) ) wp_die( esc_html__( 'Unauthorized', 'gt-bogo-engine' ) );

global $wpdb;

$tbl          = $wpdb->prefix . 'gtbogo_rules';
$table_exists = $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $tbl ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching

// Fetch all rules
$all_rules = $table_exists ? $wpdb->get_results( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
	"SELECT * FROM {$tbl} ORDER BY priority ASC, id DESC"
) : array();

// Split into custom vs pack
$custom_rules = array_filter( $all_rules, function( $r ) {
	return empty( $r->pack_source ) || $r->pack_source === 'custom';
} );
$pack_rules = array_filter( $all_rules, function( $r ) {
	return ! empty( $r->pack_source ) && $r->pack_source !== 'custom' && $r->pack_source !== 'free_rule';
} );
$custom_rules = array_values( $custom_rules );
$pack_rules   = array_values( $pack_rules );

// Nonces
$rules_nonce = wp_create_nonce( 'gtbogo_rules_nonce' );
$srch_nonce  = wp_create_nonce( 'gtbogo_product_search' );
$ajax_url    = admin_url( 'admin-ajax.php' );

// Priority conflicts in custom rules
$priorities = array_column( $custom_rules, 'priority' );
$dupes      = array_filter( array_count_values( $priorities ), fn( $c ) => $c > 1 );

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

<!-- ── Page header ───────────────────────────────────────────────── -->
<div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:24px">
	<div>
		<h1 class="gt-page-title">RULES MANAGER</h1>
		<p class="gt-page-subtitle">Custom inventory rules target your products and categories. PRO pack rules deliver industry intelligence.</p>
	</div>
	<button id="gtbrm-add-btn" onclick="gtbrmShowEditor(0)"
		style="background:#E10000;color:#fff;border:none;border-radius:8px;padding:10px 22px;font-size:14px;font-weight:700;cursor:pointer;font-family:inherit;display:flex;align-items:center;gap:8px">
		<span style="font-size:18px;line-height:1">+</span> New Inventory Rule
	</button>
</div>

<!-- ── KPI bar ───────────────────────────────────────────────────── -->
<div style="display:grid;grid-template-columns:repeat(4,1fr);gap:16px;margin-bottom:24px">
	<?php
	$total_custom  = count( $custom_rules );
	$active_custom = count( array_filter( $custom_rules, fn($r) => $r->status === 'active' ) );
	$total_pack    = count( $pack_rules );
	$active_pack   = count( array_filter( $pack_rules, fn($r) => $r->status === 'active' ) );
	$total_conv    = array_sum( array_column( $all_rules, 'conversions' ) );
	$total_rev     = array_sum( array_column( $all_rules, 'revenue_influenced' ) );
	foreach ( array(
		array( 'Custom Rules', $active_custom . '/' . $total_custom . ' active', '#3b82f6', 'Inventory targeting rules' ),
		array( 'Pack Rules', $active_pack . '/' . $total_pack . ' active', '#8b5cf6', 'Licensed PRO pack rules' ),
		array( 'Total Conversions', number_format( (int) $total_conv ), '#22c55e', 'All-time BOGO orders' ),
		array( 'Revenue Influenced', '$' . number_format( (float) $total_rev, 0 ), '#E10000', 'All-time revenue from rules' ),
	) as $kpi ) : ?>
	<div style="background:var(--gt-card);border:1px solid var(--gt-border);border-radius:12px;padding:20px 22px;position:relative;overflow:hidden">
		<div style="position:absolute;top:0;left:0;right:0;height:3px;background:<?php echo esc_attr( $kpi[2] ); ?>"></div>
		<p style="margin:0 0 8px;font-size:11px;font-weight:800;letter-spacing:.1em;text-transform:uppercase;color:var(--gt-subtle)"><?php echo esc_html( $kpi[0] ); ?></p>
		<p style="margin:0 0 4px;font-size:28px;font-weight:900;color:<?php echo esc_attr( $kpi[2] ); ?>;font-family:'DM Mono',monospace;line-height:1"><?php echo esc_html( $kpi[1] ); ?></p>
		<p style="margin:0;font-size:12px;color:var(--gt-subtle)"><?php echo esc_html( $kpi[3] ); ?></p>
	</div>
	<?php endforeach; ?>
</div>

<!-- ═══════════════════════════════════════════════════════════
     SECTION 1 — CUSTOM INVENTORY RULES
     ═══════════════════════════════════════════════════════════ -->
<div class="gt-card gt-animate-in" style="margin-bottom:28px">
	<div class="gt-card-header" style="margin-bottom:20px">
		<div>
			<h2 class="gt-card-title">🎯 Custom Inventory Rules</h2>
			<p style="margin:4px 0 0;font-size:13px;color:var(--gt-subtle)">Target specific products, categories, or tags. Create unlimited rules — one per category, product line, or deal type.</p>
		</div>
		<button onclick="gtbrmShowEditor(0)"
			style="background:rgba(225,0,0,0.12);color:#E10000;border:1px solid rgba(225,0,0,0.25);border-radius:8px;padding:8px 18px;font-size:13px;font-weight:700;cursor:pointer;font-family:inherit">
			+ New Rule
		</button>
	</div>

	<?php if ( empty( $custom_rules ) ) : ?>
	<div style="text-align:center;padding:56px 24px">
		<div style="font-size:48px;margin-bottom:16px">🎯</div>
		<div style="font-size:18px;font-weight:900;color:var(--gt-white);margin-bottom:8px;text-transform:uppercase;font-family:Outfit,sans-serif">NO CUSTOM RULES YET</div>
		<div style="font-size:14px;color:var(--gt-soft);margin-bottom:24px;max-width:420px;margin-left:auto;margin-right:auto">Create inventory rules to target specific products or categories. For example: "T-Shirts — Buy 2 Get 1 Free" or "Sweatshirts — 50% off second item".</div>
		<button onclick="gtbrmShowEditor(0)"
			style="background:#E10000;color:#fff;border:none;border-radius:8px;padding:12px 28px;font-size:15px;font-weight:700;cursor:pointer;font-family:inherit">
			Create First Rule
		</button>
	</div>
	<?php else : ?>
	<div style="overflow-x:auto">
		<table style="width:100%;border-collapse:collapse">
			<thead>
				<tr style="border-bottom:1px solid var(--gt-border)">
					<?php foreach ( array( 'Rule', 'Deal', 'Targeting', 'Schedule', 'Fires', 'Conversions', 'Revenue', 'Actions' ) as $h ) : ?>
					<th style="padding:10px 14px;text-align:<?php echo $h === 'Fires' || $h === 'Conversions' || $h === 'Revenue' ? 'center' : 'left'; ?>;font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:.06em;color:var(--gt-subtle)"><?php echo esc_html( $h ); ?></th>
					<?php endforeach; ?>
				</tr>
			</thead>
			<tbody>
			<?php foreach ( $custom_rules as $r ) :
				$cats   = array_filter( explode( ',', (string) ( $r->categories ?? '' ) ) );
				$prods  = array_filter( explode( ',', (string) ( $r->products   ?? '' ) ) );
				$tags   = array_filter( explode( ',', (string) ( $r->tags       ?? '' ) ) );
				$active = $r->status === 'active';
				$disc   = $r->discount_type === 'percentage'
					? ( (float) $r->discount_value >= 100 ? 'Free' : (int) $r->discount_value . '% off' )
					: '$' . number_format( (float) $r->discount_value, 2 ) . ' off';
				$start_d = $r->start_date ? substr( $r->start_date, 0, 10 ) : '';
				$end_d   = $r->end_date   ? substr( $r->end_date,   0, 10 ) : '';
				$has_conflict = isset( $dupes[ (int) $r->priority ] );
			?>
			<tr id="gtbrm-row-<?php echo (int) $r->id; ?>"
				style="border-bottom:1px solid var(--gt-border);transition:background .15s"
				onmouseover="this.style.background='rgba(255,255,255,0.02)'"
				onmouseout="this.style.background=''">
				<td style="padding:14px">
					<div style="font-weight:700;color:var(--gt-white);margin-bottom:5px"><?php echo esc_html( $r->name ); ?></div>
					<span id="gtbrm-badge-<?php echo (int) $r->id; ?>" style="display:inline-block;padding:2px 8px;border-radius:4px;font-size:11px;font-weight:700;
						background:<?php echo $active ? 'rgba(34,197,94,0.12)' : 'rgba(100,116,139,0.15)'; ?>;
						color:<?php echo $active ? '#22c55e' : '#64748b'; ?>">
						<?php echo $active ? 'Active' : 'Paused'; ?>
					</span>
					<?php if ( $has_conflict ) : ?>
					<span style="display:inline-block;padding:2px 6px;border-radius:4px;font-size:11px;font-weight:700;background:rgba(245,158,11,0.12);color:#f59e0b;margin-left:4px" title="Priority conflict">⚠ P<?php echo (int) $r->priority; ?></span>
					<?php endif; ?>
				</td>
				<td style="padding:14px;font-size:14px;color:rgba(255,255,255,0.9)">
					Buy <?php echo (int) $r->buy_quantity; ?> get <?php echo (int) $r->get_quantity; ?>
					<strong style="color:var(--gt-white);display:block;font-size:13px"><?php echo esc_html( $disc ); ?></strong>
				</td>
				<td style="padding:14px;font-size:13px;color:var(--gt-subtle)">
					<?php if ( empty( $cats ) && empty( $prods ) && empty( $tags ) ) : ?>
						<span style="color:#22c55e;font-weight:600">All products</span>
					<?php else : ?>
						<?php if ( ! empty( $cats ) ) echo '<div>' . count( $cats ) . ' ' . ( count( $cats ) === 1 ? 'category' : 'categories' ) . '</div>'; ?>
						<?php if ( ! empty( $prods ) ) echo '<div>' . count( $prods ) . ' ' . ( count( $prods ) === 1 ? 'product' : 'products' ) . '</div>'; ?>
						<?php if ( ! empty( $tags ) ) echo '<div>' . count( $tags ) . ' ' . ( count( $tags ) === 1 ? 'tag' : 'tags' ) . '</div>'; ?>
					<?php endif; ?>
					<?php if ( ! empty( $r->exclude_sale ) ) : ?>
						<div style="color:#f59e0b;font-size:11px;margin-top:3px">Excl. sale items</div>
					<?php endif; ?>
				</td>
				<td style="padding:14px;font-size:12px;color:var(--gt-subtle)">
					<?php if ( $start_d || $end_d ) : ?>
						<?php echo $start_d ? esc_html( $start_d ) : '—'; ?><br>
						<span style="opacity:.6">to <?php echo $end_d ? esc_html( $end_d ) : 'no end'; ?></span>
					<?php else : ?>
						<span style="color:#22c55e">Always on</span>
					<?php endif; ?>
				</td>
				<td style="padding:14px;text-align:center;font-size:20px;font-weight:900;color:#3b82f6;font-family:'DM Mono',monospace"><?php echo number_format( (int) $r->impressions ); ?></td>
				<td style="padding:14px;text-align:center;font-size:20px;font-weight:900;color:#22c55e;font-family:'DM Mono',monospace"><?php echo number_format( (int) $r->conversions ); ?></td>
				<td style="padding:14px;text-align:center;font-size:15px;font-weight:700;color:#E10000;font-family:'DM Mono',monospace">$<?php echo number_format( (float) $r->revenue_influenced, 0 ); ?></td>
				<td style="padding:14px;white-space:nowrap">
					<button onclick="gtbrmShowEditor(<?php echo (int) $r->id; ?>)"
						style="background:rgba(255,255,255,0.06);color:#fff;border:none;border-radius:6px;padding:6px 12px;font-size:12px;cursor:pointer;margin-right:4px;font-family:inherit">Edit</button>
					<button id="gtbrm-toggle-<?php echo (int) $r->id; ?>"
						onclick="gtbrmToggle(<?php echo (int) $r->id; ?>,this)"
						data-status="<?php echo esc_attr( $r->status ); ?>"
						style="background:rgba(255,255,255,0.06);color:<?php echo $active ? '#f59e0b' : '#22c55e'; ?>;border:none;border-radius:6px;padding:6px 12px;font-size:12px;cursor:pointer;margin-right:4px;font-family:inherit">
						<?php echo $active ? 'Pause' : 'Activate'; ?>
					</button>
					<button onclick="gtbrmDelete(<?php echo (int) $r->id; ?>,<?php echo esc_js( $r->name ); ?>)"
						style="background:rgba(239,68,68,0.1);color:#ef4444;border:none;border-radius:6px;padding:6px 12px;font-size:12px;cursor:pointer;font-family:inherit">Delete</button>
				</td>
			</tr>
			<?php endforeach; ?>
			</tbody>
		</table>
	</div>
	<?php endif; ?>
</div>

<!-- ── Rule Editor (custom rules only) ─────────────────────── -->
<div id="gtbrm-editor" class="gt-card gt-animate-in" style="display:none;margin-bottom:28px;border:1px solid rgba(225,0,0,0.2)">
	<div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:20px">
		<h2 class="gt-card-title" id="gtbrm-editor-title">New Inventory Rule</h2>
		<button onclick="gtbrmHideEditor()"
			style="background:rgba(255,255,255,0.06);color:#fff;border:none;border-radius:6px;padding:6px 16px;font-size:13px;cursor:pointer;font-family:inherit">✕ Cancel</button>
	</div>
	<input type="hidden" id="gtbrm-id" value="0">

	<!-- Row 1: Name + Priority -->
	<div style="display:grid;grid-template-columns:1fr 120px;gap:16px;margin-bottom:16px">
		<div>
			<label class="gt-form-label">Rule Name <span style="color:#ef4444">*</span></label>
			<input type="text" id="gtbrm-name" class="gt-input" placeholder="e.g. T-Shirts BOGO, Sweatshirts 50% Off">
		</div>
		<div>
			<label class="gt-form-label">Priority</label>
			<input type="number" id="gtbrm-priority" class="gt-input" value="10" min="1" max="100">
			<div style="font-size:11px;color:var(--gt-subtle);margin-top:4px">Lower = higher priority</div>
		</div>
	</div>

	<!-- Row 2: Deal structure -->
	<div style="display:grid;grid-template-columns:repeat(4,1fr);gap:16px;margin-bottom:16px">
		<div>
			<label class="gt-form-label">Buy Quantity</label>
			<input type="number" id="gtbrm-buy" class="gt-input" value="1" min="1" max="99">
		</div>
		<div>
			<label class="gt-form-label">Get Quantity</label>
			<input type="number" id="gtbrm-get" class="gt-input" value="1" min="1" max="99">
		</div>
		<div>
			<label class="gt-form-label">Discount Type</label>
			<select id="gtbrm-disc-type" class="gt-input">
				<option value="percentage">Percentage %</option>
				<option value="fixed">Fixed Amount $</option>
			</select>
		</div>
		<div>
			<label class="gt-form-label">Discount Value</label>
			<input type="number" id="gtbrm-disc-val" class="gt-input" value="100" min="0" max="100" step="0.01">
			<div style="font-size:11px;color:var(--gt-subtle);margin-top:4px">100% = free item</div>
		</div>
	</div>

	<!-- Row 3: Options -->
	<div style="display:grid;grid-template-columns:repeat(4,1fr);gap:16px;margin-bottom:16px">
		<div>
			<label class="gt-form-label">Apply Discount To</label>
			<select id="gtbrm-apply-to" class="gt-input">
				<option value="cheapest">Cheapest item</option>
				<option value="most_exp">Most expensive</option>
			</select>
		</div>
		<div>
			<label class="gt-form-label">Min Cart Total ($)</label>
			<input type="number" id="gtbrm-min-cart" class="gt-input" value="0" min="0" step="0.01">
		</div>
		<div>
			<label class="gt-form-label">Max Uses / Order</label>
			<input type="number" id="gtbrm-max-uses" class="gt-input" value="1" min="1" max="99">
		</div>
		<div style="display:flex;align-items:flex-end;padding-bottom:2px">
			<label style="display:flex;align-items:center;gap:8px;cursor:pointer;font-size:13px;color:var(--gt-soft)">
				<input type="checkbox" id="gtbrm-exclude-sale" style="width:16px;height:16px;accent-color:#E10000">
				Exclude sale items
			</label>
		</div>
	</div>

	<!-- Row 4: Scheduling -->
	<div style="display:grid;grid-template-columns:1fr 1fr;gap:16px;margin-bottom:24px">
		<div>
			<label class="gt-form-label">Active From (optional)</label>
			<input type="date" id="gtbrm-start" class="gt-input" style="color-scheme:dark">
		</div>
		<div>
			<label class="gt-form-label">Active Until (optional)</label>
			<input type="date" id="gtbrm-end" class="gt-input" style="color-scheme:dark">
		</div>
	</div>

	<!-- Targeting -->
	<div style="border-top:1px solid var(--gt-border);padding-top:20px;margin-bottom:20px">
		<div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:4px">
			<h3 style="margin:0;font-size:15px;font-weight:800;color:var(--gt-white)">Product Targeting</h3>
			<span style="font-size:12px;color:var(--gt-subtle)">Leave all empty to apply to all products</span>
		</div>
		<p style="font-size:13px;color:var(--gt-subtle);margin:6px 0 20px">Set targeting to restrict this rule to specific products, categories, or tags. Perfect for "T-Shirts only" or "Winter Collection" deals.</p>
	</div>

	<!-- Categories -->
	<div style="margin-bottom:20px">
		<label class="gt-form-label">Categories</label>
		<div id="gtbrm-cats-chips" style="display:flex;flex-wrap:wrap;gap:6px;min-height:28px;margin-bottom:8px"></div>
		<input type="text" id="gtbrm-cat-search" class="gt-input" placeholder="Search categories..." style="margin-bottom:6px" autocomplete="off">
		<div id="gtbrm-cat-results" style="background:rgba(255,255,255,0.04);border:1px solid var(--gt-border);border-radius:8px;max-height:180px;overflow-y:auto;display:none"></div>
		<input type="hidden" id="gtbrm-categories" value="">
	</div>

	<!-- Products -->
	<div style="margin-bottom:20px">
		<label class="gt-form-label">Specific Products</label>
		<div id="gtbrm-prods-chips" style="display:flex;flex-wrap:wrap;gap:6px;min-height:28px;margin-bottom:8px"></div>
		<input type="text" id="gtbrm-prod-search" class="gt-input" placeholder="Search by name or SKU..." style="margin-bottom:6px" autocomplete="off">
		<div id="gtbrm-prod-results" style="background:rgba(255,255,255,0.04);border:1px solid var(--gt-border);border-radius:8px;max-height:200px;overflow-y:auto;display:none"></div>
		<input type="hidden" id="gtbrm-products" value="">
	</div>

	<!-- Tags -->
	<div style="margin-bottom:24px">
		<label class="gt-form-label">Tags</label>
		<div id="gtbrm-tags-chips" style="display:flex;flex-wrap:wrap;gap:6px;min-height:28px;margin-bottom:8px"></div>
		<input type="text" id="gtbrm-tag-search" class="gt-input" placeholder="Search product tags..." style="margin-bottom:6px" autocomplete="off">
		<div id="gtbrm-tag-results" style="background:rgba(255,255,255,0.04);border:1px solid var(--gt-border);border-radius:8px;max-height:180px;overflow-y:auto;display:none"></div>
		<input type="hidden" id="gtbrm-tags" value="">
	</div>

	<!-- Save bar -->
	<div style="display:flex;gap:12px;align-items:center;padding-top:16px;border-top:1px solid var(--gt-border)">
		<button id="gtbrm-save-btn" onclick="gtbrmSave()"
			style="background:#E10000;color:#fff;border:none;border-radius:8px;padding:12px 28px;font-size:15px;font-weight:700;cursor:pointer;font-family:inherit">
			Save Rule
		</button>
		<button onclick="gtbrmHideEditor()"
			style="background:rgba(255,255,255,0.06);color:#fff;border:none;border-radius:8px;padding:12px 20px;font-size:14px;cursor:pointer;font-family:inherit">Cancel</button>
		<span id="gtbrm-status" style="font-size:13px;color:var(--gt-subtle)"></span>
	</div>
</div>

<!-- ═══════════════════════════════════════════════════════════
     SECTION 2 — PRO PACK RULES (read-only, toggle only)
     ═══════════════════════════════════════════════════════════ -->
<div class="gt-card gt-animate-in" style="margin-bottom:24px">
	<div class="gt-card-header" style="margin-bottom:20px">
		<div>
			<h2 class="gt-card-title">🔒 PRO Pack Rules</h2>
			<p style="margin:4px 0 0;font-size:13px;color:var(--gt-subtle)"><?php echo count( $pack_rules ); ?> rules from licensed packs. Toggle on/off — editing is locked to protect your licensed intelligence.</p>
		</div>
		<a href="<?php echo esc_url( admin_url( 'admin.php?page=gt-bogo-engine&tab=pro-rules' ) ); ?>"
			style="background:rgba(139,92,246,0.12);color:#a78bfa;border:1px solid rgba(139,92,246,0.25);border-radius:8px;padding:8px 18px;font-size:13px;font-weight:700;text-decoration:none">
			Manage Packs →
		</a>
	</div>

	<?php if ( empty( $pack_rules ) ) : ?>
	<div style="text-align:center;padding:40px 24px">
		<div style="font-size:40px;margin-bottom:12px">📦</div>
		<div style="font-size:16px;font-weight:800;color:var(--gt-white);margin-bottom:8px">No pack rules installed</div>
		<div style="font-size:13px;color:var(--gt-soft);margin-bottom:20px">Purchase PRO packs to unlock 200 expert-built rules across 19 industries.</div>
		<a href="<?php echo esc_url( admin_url( 'admin.php?page=gt-bogo-engine&tab=pro-rules' ) ); ?>"
			style="display:inline-block;background:#8b5cf6;color:#fff;border-radius:8px;padding:10px 22px;font-size:14px;font-weight:700;text-decoration:none">
			Browse PRO Packs
		</a>
	</div>
	<?php else : ?>
	<div style="overflow-x:auto">
		<table style="width:100%;border-collapse:collapse">
			<thead>
				<tr style="border-bottom:1px solid var(--gt-border)">
					<?php foreach ( array( 'Rule', 'Pack Source', 'Deal', 'Fires', 'Conversions', 'Status', '' ) as $h ) : ?>
					<th style="padding:10px 14px;text-align:left;font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:.06em;color:var(--gt-subtle)"><?php echo esc_html( $h ); ?></th>
					<?php endforeach; ?>
				</tr>
			</thead>
			<tbody>
			<?php foreach ( $pack_rules as $r ) :
				$active = $r->status === 'active';
				$disc   = $r->discount_type === 'percentage'
					? ( (float) $r->discount_value >= 100 ? 'Free' : (int) $r->discount_value . '%' )
					: '$' . number_format( (float) $r->discount_value, 2 );
			?>
			<tr id="gtbrm-packrow-<?php echo (int) $r->id; ?>"
				style="border-bottom:1px solid var(--gt-border);opacity:<?php echo $active ? '1' : '.55'; ?>;transition:opacity .2s">
				<td style="padding:12px 14px">
					<div style="font-weight:700;color:var(--gt-white);margin-bottom:3px"><?php echo esc_html( $r->name ); ?></div>
					<span style="font-size:11px;color:var(--gt-subtle);display:flex;align-items:center;gap:4px">🔒 Licensed</span>
				</td>
				<td style="padding:12px 14px">
					<span style="background:rgba(139,92,246,0.1);border:1px solid rgba(139,92,246,0.2);color:#a78bfa;padding:2px 8px;border-radius:50px;font-size:12px;font-weight:700"><?php echo esc_html( $r->pack_source ); ?></span>
				</td>
				<td style="padding:12px 14px;font-size:13px;color:rgba(255,255,255,0.8)">
					Buy <?php echo (int) $r->buy_quantity; ?> → <?php echo (int) $r->get_quantity; ?>
					<strong style="color:var(--gt-white)"> <?php echo esc_html( $disc ); ?> off</strong>
				</td>
				<td style="padding:12px 14px;font-size:16px;font-weight:700;color:#3b82f6;font-family:'DM Mono',monospace"><?php echo number_format( (int) $r->impressions ); ?></td>
				<td style="padding:12px 14px;font-size:16px;font-weight:700;color:#22c55e;font-family:'DM Mono',monospace"><?php echo number_format( (int) $r->conversions ); ?></td>
				<td style="padding:12px 14px">
					<span id="gtbrm-pack-badge-<?php echo (int) $r->id; ?>" style="display:inline-block;padding:2px 8px;border-radius:4px;font-size:11px;font-weight:700;
						background:<?php echo $active ? 'rgba(34,197,94,0.12)' : 'rgba(100,116,139,0.15)'; ?>;
						color:<?php echo $active ? '#22c55e' : '#64748b'; ?>">
						<?php echo $active ? '● Active' : '○ Paused'; ?>
					</span>
				</td>
				<td style="padding:12px 14px">
					<button id="gtbrm-pack-toggle-<?php echo (int) $r->id; ?>"
						onclick="gtbrmTogglePack(<?php echo (int) $r->id; ?>,this)"
						data-status="<?php echo esc_attr( $r->status ); ?>"
						style="background:rgba(255,255,255,0.06);color:<?php echo $active ? '#f59e0b' : '#22c55e'; ?>;border:none;border-radius:6px;padding:5px 12px;font-size:12px;cursor:pointer;font-family:inherit">
						<?php echo $active ? 'Pause' : 'Activate'; ?>
					</button>
				</td>
			</tr>
			<?php endforeach; ?>
			</tbody>
		</table>
	</div>
	<?php endif; ?>
</div>

<?php
// Inline JS — enterprise AJAX logic
$page_js = wp_json_encode( array(
	'nonce'    => $rules_nonce,
	'snonce'   => $srch_nonce,
	'ajaxUrl'  => $ajax_url,
) );
?>
<script>
var gtbrmData = <?php echo $page_js; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>;
var gtbrmCatMap = {}, gtbrmProdMap = {}, gtbrmTagMap = {};

// ── Editor show/hide ──────────────────────────────────────────
function gtbrmShowEditor(id) {
	document.getElementById('gtbrm-editor').style.display = 'block';
	document.getElementById('gtbrm-editor').scrollIntoView({behavior:'smooth',block:'start'});
	if (id === 0) {
		document.getElementById('gtbrm-editor-title').textContent = 'New Inventory Rule';
		gtbrmResetEditor();
	} else {
		document.getElementById('gtbrm-editor-title').textContent = 'Edit Rule';
		gtbrmLoadRule(id);
	}
}
function gtbrmHideEditor() {
	document.getElementById('gtbrm-editor').style.display = 'none';
	gtbrmResetEditor();
}
function gtbrmResetEditor() {
	document.getElementById('gtbrm-id').value = '0';
	document.getElementById('gtbrm-name').value = '';
	document.getElementById('gtbrm-priority').value = '10';
	document.getElementById('gtbrm-buy').value = '1';
	document.getElementById('gtbrm-get').value = '1';
	document.getElementById('gtbrm-disc-type').value = 'percentage';
	document.getElementById('gtbrm-disc-val').value = '100';
	document.getElementById('gtbrm-apply-to').value = 'cheapest';
	document.getElementById('gtbrm-min-cart').value = '0';
	document.getElementById('gtbrm-max-uses').value = '1';
	document.getElementById('gtbrm-exclude-sale').checked = false;
	document.getElementById('gtbrm-start').value = '';
	document.getElementById('gtbrm-end').value = '';
	document.getElementById('gtbrm-categories').value = '';
	document.getElementById('gtbrm-products').value = '';
	document.getElementById('gtbrm-tags').value = '';
	document.getElementById('gtbrm-cats-chips').innerHTML = '';
	document.getElementById('gtbrm-prods-chips').innerHTML = '';
	document.getElementById('gtbrm-tags-chips').innerHTML = '';
	document.getElementById('gtbrm-status').textContent = '';
	gtbrmCatMap = {}; gtbrmProdMap = {}; gtbrmTagMap = {};
}

// ── Load rule for editing ─────────────────────────────────────
function gtbrmLoadRule(id) {
	var fd = new FormData();
	fd.append('action','gtbogo_get_rule');
	fd.append('nonce', gtbrmData.nonce);
	fd.append('rule_id', id);
	fetch(gtbrmData.ajaxUrl, {method:'POST',body:fd})
		.then(r=>r.json()).then(function(res) {
			if (!res.success) return;
			var r = res.data;
			document.getElementById('gtbrm-id').value = r.id;
			document.getElementById('gtbrm-name').value = r.name || '';
			document.getElementById('gtbrm-priority').value = r.priority || 10;
			document.getElementById('gtbrm-buy').value = r.buy_quantity || 1;
			document.getElementById('gtbrm-get').value = r.get_quantity || 1;
			document.getElementById('gtbrm-disc-type').value = r.discount_type || 'percentage';
			document.getElementById('gtbrm-disc-val').value = r.discount_value || 100;
			document.getElementById('gtbrm-apply-to').value = r.apply_to || 'cheapest';
			document.getElementById('gtbrm-min-cart').value = r.min_cart_total || 0;
			document.getElementById('gtbrm-max-uses').value = r.max_uses || 1;
			document.getElementById('gtbrm-exclude-sale').checked = !!parseInt(r.exclude_sale);
			document.getElementById('gtbrm-start').value = r.start_date || '';
			document.getElementById('gtbrm-end').value = r.end_date || '';
			// Restore targeting chips from stored IDs (names loaded separately via inventory API)
			document.getElementById('gtbrm-categories').value = r.categories || '';
			document.getElementById('gtbrm-products').value = r.products || '';
			document.getElementById('gtbrm-tags').value = r.tags || '';
		});
}

// ── Save rule ─────────────────────────────────────────────────
function gtbrmSave() {
	var name = document.getElementById('gtbrm-name').value.trim();
	if (!name) { alert('Please enter a rule name.'); return; }
	var btn = document.getElementById('gtbrm-save-btn');
	var st  = document.getElementById('gtbrm-status');
	btn.disabled = true; btn.textContent = 'Saving…';
	var fd = new FormData();
	fd.append('action','gtbogo_save_rule');
	fd.append('nonce', gtbrmData.nonce);
	fd.append('rule_id', document.getElementById('gtbrm-id').value);
	fd.append('name', name);
	fd.append('priority', document.getElementById('gtbrm-priority').value);
	fd.append('buy_quantity', document.getElementById('gtbrm-buy').value);
	fd.append('get_quantity', document.getElementById('gtbrm-get').value);
	fd.append('discount_type', document.getElementById('gtbrm-disc-type').value);
	fd.append('discount_value', document.getElementById('gtbrm-disc-val').value);
	fd.append('apply_to', document.getElementById('gtbrm-apply-to').value);
	fd.append('min_cart_total', document.getElementById('gtbrm-min-cart').value);
	fd.append('max_uses', document.getElementById('gtbrm-max-uses').value);
	fd.append('exclude_sale', document.getElementById('gtbrm-exclude-sale').checked ? '1' : '0');
	fd.append('start_date', document.getElementById('gtbrm-start').value);
	fd.append('end_date', document.getElementById('gtbrm-end').value);
	fd.append('categories', document.getElementById('gtbrm-categories').value);
	fd.append('products', document.getElementById('gtbrm-products').value);
	fd.append('tags', document.getElementById('gtbrm-tags').value);
	fetch(gtbrmData.ajaxUrl, {method:'POST',body:fd})
		.then(r=>r.json()).then(function(res) {
			btn.disabled = false; btn.textContent = 'Save Rule';
			if (res.success) {
				st.style.color = '#22c55e';
				st.textContent = '✓ Saved — reloading…';
				setTimeout(function(){ location.reload(); }, 800);
			} else {
				st.style.color = '#ef4444';
				st.textContent = res.data && res.data.message ? res.data.message : 'Error saving rule.';
			}
		});
}

// ── Toggle custom rule ────────────────────────────────────────
function gtbrmToggle(id, btn) {
	var fd = new FormData();
	fd.append('action','gtbogo_toggle_rule');
	fd.append('nonce', gtbrmData.nonce);
	fd.append('rule_id', id);
	fetch(gtbrmData.ajaxUrl, {method:'POST',body:fd})
		.then(r=>r.json()).then(function(res) {
			if (!res.success) return;
			var active = res.data.status === 'active';
			var row = document.getElementById('gtbrm-row-' + id);
			var badge = document.getElementById('gtbrm-badge-' + id);
			if (badge) {
				badge.textContent = active ? 'Active' : 'Paused';
				badge.style.background = active ? 'rgba(34,197,94,0.12)' : 'rgba(100,116,139,0.15)';
				badge.style.color = active ? '#22c55e' : '#64748b';
			}
			btn.dataset.status = res.data.status;
			btn.textContent = active ? 'Pause' : 'Activate';
			btn.style.color = active ? '#f59e0b' : '#22c55e';
		});
}

// ── Toggle pack rule ──────────────────────────────────────────
function gtbrmTogglePack(id, btn) {
	var fd = new FormData();
	fd.append('action','gtbogo_toggle_rule');
	fd.append('nonce', gtbrmData.nonce);
	fd.append('rule_id', id);
	fetch(gtbrmData.ajaxUrl, {method:'POST',body:fd})
		.then(r=>r.json()).then(function(res) {
			if (!res.success) return;
			var active = res.data.status === 'active';
			var row = document.getElementById('gtbrm-packrow-' + id);
			var badge = document.getElementById('gtbrm-pack-badge-' + id);
			if (row) row.style.opacity = active ? '1' : '0.55';
			if (badge) {
				badge.textContent = active ? '● Active' : '○ Paused';
				badge.style.background = active ? 'rgba(34,197,94,0.12)' : 'rgba(100,116,139,0.15)';
				badge.style.color = active ? '#22c55e' : '#64748b';
			}
			btn.textContent = active ? 'Pause' : 'Activate';
			btn.style.color = active ? '#f59e0b' : '#22c55e';
		});
}

// ── Delete custom rule ────────────────────────────────────────
function gtbrmDelete(id, name) {
	if (!confirm('Delete rule "' + name + '"? This cannot be undone.')) return;
	var fd = new FormData();
	fd.append('action','gtbogo_delete_rule');
	fd.append('nonce', gtbrmData.nonce);
	fd.append('rule_id', id);
	fetch(gtbrmData.ajaxUrl, {method:'POST',body:fd})
		.then(r=>r.json()).then(function(res) {
			if (res.success) {
				var row = document.getElementById('gtbrm-row-' + id);
				if (row) row.remove();
			}
		});
}

// ── Search helpers (categories, products, tags) ───────────────
function gtbrmDebounce(fn, ms) {
	var t; return function() { clearTimeout(t); t = setTimeout(fn, ms); };
}

function gtbrmAddChip(type, id, name) {
	var map = type==='cat' ? gtbrmCatMap : type==='prod' ? gtbrmProdMap : gtbrmTagMap;
	var container = document.getElementById('gtbrm-' + (type==='cat'?'cats':type==='prod'?'prods':'tags') + '-chips');
	var hiddenId = 'gtbrm-' + (type==='cat'?'categories':type==='prod'?'products':'tags');
	if (map[id]) return;
	map[id] = name;
	var chip = document.createElement('span');
	chip.style.cssText = 'display:inline-flex;align-items:center;gap:6px;background:rgba(59,130,246,0.12);border:1px solid rgba(59,130,246,0.25);color:#93c5fd;padding:4px 10px;border-radius:20px;font-size:12px;font-weight:600';
	chip.innerHTML = name + ' <button onclick="gtbrmRemoveChip(\'' + type + '\',' + id + ',this)" style="background:none;border:none;color:#93c5fd;cursor:pointer;font-size:14px;line-height:1;padding:0">×</button>';
	container.appendChild(chip);
	gtbrmUpdateHidden(type, hiddenId, map);
}

function gtbrmRemoveChip(type, id, btn) {
	var map = type==='cat' ? gtbrmCatMap : type==='prod' ? gtbrmProdMap : gtbrmTagMap;
	var hiddenId = 'gtbrm-' + (type==='cat'?'categories':type==='prod'?'products':'tags');
	delete map[id];
	btn.parentElement.remove();
	gtbrmUpdateHidden(type, hiddenId, map);
}

function gtbrmUpdateHidden(type, hiddenId, map) {
	document.getElementById(hiddenId).value = Object.keys(map).join(',');
}

function gtbrmSearch(type, q) {
	if (q.length < 2) { document.getElementById('gtbrm-' + (type==='cat'?'cat':type==='prod'?'prod':'tag') + '-results').style.display='none'; return; }
	var action = type==='prod' ? 'gtbogo_search_products' : (type==='cat' ? 'gtbogo_search_categories' : 'gtbogo_search_categories');
	var fd = new FormData();
	fd.append('action', action);
	fd.append('nonce', gtbrmData.snonce);
	fd.append('q', q);
	if (type==='tag') fd.append('taxonomy','product_tag');
	fetch(gtbrmData.ajaxUrl, {method:'POST',body:fd})
		.then(r=>r.json()).then(function(res) {
			var rid = 'gtbrm-' + (type==='cat'?'cat':type==='prod'?'prod':'tag') + '-results';
			var el = document.getElementById(rid);
			if (!res.success || !res.data.length) { el.style.display='none'; return; }
			el.innerHTML = res.data.map(function(item) {
				return '<div onclick="gtbrmAddChip(\'' + type + '\',' + item.id + ',\'' + item.name.replace(/'/g,"\\'") + '\');document.getElementById(\'' + rid + '\').style.display=\'none\'" style="padding:10px 14px;cursor:pointer;font-size:13px;border-bottom:1px solid var(--gt-border)" onmouseover="this.style.background=\'rgba(255,255,255,0.04)\'" onmouseout="this.style.background=\'\'">' + item.name + (item.count !== undefined ? ' <span style=\'color:var(--gt-subtle);font-size:11px\'>(' + item.count + ')</span>' : '') + '</div>';
			}).join('');
			el.style.display = 'block';
		});
}

// Wire search inputs
document.addEventListener('DOMContentLoaded', function() {
	var catSrch = document.getElementById('gtbrm-cat-search');
	var prodSrch = document.getElementById('gtbrm-prod-search');
	var tagSrch = document.getElementById('gtbrm-tag-search');
	if (catSrch) catSrch.addEventListener('input', gtbrmDebounce(function(){ gtbrmSearch('cat', catSrch.value); }, 300));
	if (prodSrch) prodSrch.addEventListener('input', gtbrmDebounce(function(){ gtbrmSearch('prod', prodSrch.value); }, 300));
	if (tagSrch) tagSrch.addEventListener('input', gtbrmDebounce(function(){ gtbrmSearch('tag', tagSrch.value); }, 300));
	// Close dropdowns on outside click
	document.addEventListener('click', function(e) {
		['gtbrm-cat-results','gtbrm-prod-results','gtbrm-tag-results'].forEach(function(id) {
			var el = document.getElementById(id);
			if (el && !el.contains(e.target) && e.target.id !== 'gtbrm-cat-search' && e.target.id !== 'gtbrm-prod-search' && e.target.id !== 'gtbrm-tag-search') {
				el.style.display = 'none';
			}
		});
	});
});
</script>

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