<?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 — Rule Conditions Engine
 *
 * Visual condition builder:
 *   - Product categories (multi-select checkboxes with search)
 *   - Product tags (multi-select checkboxes with search)
 *   - Cart value range (min/max with real-time plain-English preview)
 *   - Day of week schedule (7-button toggle)
 *   - Time window (from/to)
 *   - Exclude sale items toggle
 *   - Exclude specific products (AJAX search)
 *   - AND / OR mode selector
 *   - Signal Bus conditions (24 signals with slider thresholds)
 *   - Archetype conditions (select 1+ archetypes to target)
 *   - Geo condition (country codes)
 *   - Subscription status condition
 *   - Live plain-English condition preview (updates as you type)
 *   - AJAX test against live cart session
 *   - Condition templates (quick-apply presets)
 *   - Export / import conditions JSON
 *
 * Saves to: gtbogo_rule_conditions (WP option)
 *
 * @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;
$nonce   = wp_create_nonce( 'gtbogo_conditions' );
$message = '';

/* ── Save ─────────────────────────────────────────────────────────────────── */
if ( $is_pro && isset( $_POST['gtbogo_save_conditions'] ) && check_admin_referer( 'gtbogo_conditions', 'gtbogo_conditions_nonce' ) ) {
	$c = array(
		'categories'        => array_map( 'absint', (array) ( $_POST['condition_categories'] ?? array() ) ),
		'tags'              => array_map( 'absint', (array) ( $_POST['condition_tags'] ?? array() ) ),
		'min_cart'          => (float) ( $_POST['condition_min_cart'] ?? 0 ),
		'max_cart'          => (float) ( $_POST['condition_max_cart'] ?? 0 ),
		'days'              => array_map( 'sanitize_key', (array) ( $_POST['condition_days'] ?? array() ) ),
		'time_start'        => sanitize_text_field( wp_unslash( $_POST['condition_time_start'] ?? '00:00' ) ),
		'time_end'          => sanitize_text_field( wp_unslash( $_POST['condition_time_end'] ?? '23:59' ) ),
		'exclude_sale'      => isset( $_POST['condition_exclude_sale'] ),
		'exclude_products'  => array_map( 'absint', (array) ( $_POST['condition_exclude_products'] ?? array() ) ),
		'mode'              => sanitize_key( wp_unslash( $_POST['condition_mode'] ?? 'all' ) ),
		'archetypes'        => array_map( 'sanitize_key', (array) ( $_POST['condition_archetypes'] ?? array() ) ),
		'geo_countries'     => array_map( 'sanitize_text_field', (array) ( $_POST['condition_geo'] ?? array() ) ),
		'require_sub'       => isset( $_POST['condition_require_sub'] ),
		'signal_thresholds' => array(),
	);

	/* Signal thresholds */
	foreach ( (array) ( $_POST['cond_signal'] ?? array() ) as $sig_key => $thresh ) { // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- sanitized inside loop body
		$c['signal_thresholds'][ sanitize_key( $sig_key ) ] = (float) $thresh;
	}

	update_option( 'gtbogo_rule_conditions', $c );
	$message = 'Conditions saved. All active rules now enforce these conditions.';
}

/* ── Load ─────────────────────────────────────────────────────────────────── */
$c = get_option(
	'gtbogo_rule_conditions',
	array(
		'categories'        => array(),
		'tags'              => array(),
		'min_cart'          => 0,
		'max_cart'          => 0,
		'days'              => array(),
		'time_start'        => '00:00',
		'time_end'          => '23:59',
		'exclude_sale'      => false,
		'exclude_products'  => array(),
		'mode'              => 'all',
		'archetypes'        => array(),
		'geo_countries'     => array(),
		'require_sub'       => false,
		'signal_thresholds' => array(),
	)
);

/* ── Terms for selectors ─────────────────────────────────────────────────── */
$all_cats = get_terms(
	array(
		'taxonomy'   => 'product_cat',
		'hide_empty' => false,
		'orderby'    => 'count',
		'order'      => 'DESC',
		'number'     => 0,
	)
);
$all_tags = get_terms(
	array(
		'taxonomy'   => 'product_tag',
		'hide_empty' => false,
		'orderby'    => 'count',
		'order'      => 'DESC',
		'number'     => 0,
	)
);

$selected_cats       = array_map( 'intval', (array) ( $c['categories'] ?? array() ) );
$selected_tags       = array_map( 'intval', (array) ( $c['tags'] ?? array() ) );
$selected_days       = array_map( 'strval', (array) ( $c['days'] ?? array() ) );
$selected_archetypes = array_map( 'strval', (array) ( $c['archetypes'] ?? array() ) );
$selected_geo        = array_map( 'strval', (array) ( $c['geo_countries'] ?? array() ) );
$signal_thresholds   = (array) ( $c['signal_thresholds'] ?? array() );

$days_of_week = array(
	'mon' => 'Mon',
	'tue' => 'Tue',
	'wed' => 'Wed',
	'thu' => 'Thu',
	'fri' => 'Fri',
	'sat' => 'Sat',
	'sun' => 'Sun',
);

$archetypes = array(
	'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',
);

/* ── 24 Signal Bus keys for sliders ─────────────────────────────────────── */
$signals = array(
	'timing_confidence'       => 'Timing Confidence',
	'price_sensitivity_score' => 'Price Sensitivity',
	'inventory_pressure'      => 'Inventory Pressure',
	'loyalty_tier'            => 'Loyalty Tier',
	'streak_engagement'       => 'Streak Engagement',
	'vip_status'              => 'VIP Status',
	'ltv_score'               => 'LTV Score',
	'rfm_score'               => 'RFM Score',
	'geo_match'               => 'Geo Match',
	'profile_depth'           => 'Profile Depth',
	'attribution_confidence'  => 'Attribution Confidence',
	'revenue_health'          => 'Revenue Health',
);

/* ── Condition templates ─────────────────────────────────────────────────── */
$templates = array(
	array( 'Weekends Only', array( 'days' => array( 'sat', 'sun' ) ) ),
	array( 'High Cart Value', array( 'min_cart' => 100 ) ),
	array( 'No Sale Items', array( 'exclude_sale' => true ) ),
	array( 'VIP + High Intent', array( 'archetypes' => array( 'vip_active', 'high_intent' ) ) ),
	array(
		'Business Hours',
		array(
			'time_start' => '09:00',
			'time_end'   => '17:00',
			'days'       => array( 'mon', 'tue', 'wed', 'thu', 'fri' ),
		),
	),
);

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">🎛 Rule Conditions Engine</h1>
		<p class="gt-page-subtitle">
			Global conditions applied to all active rules — categories, cart value,
			schedule, archetypes, geo, and Signal Bus thresholds.
		</p>
	</div>
	<div style="display:flex;gap:8px;flex-wrap:wrap">
		<button type="button" class="gt-btn gt-btn-ghost gt-btn-sm"
			onclick="gtCondTestCart('<?php echo esc_js( $nonce ); ?>')">
			🔬 Test Live Cart
		</button>
		<button type="button" class="gt-btn gt-btn-ghost gt-btn-sm"
			onclick="window.open(ajaxurl+'?action=gtbogo_cond_export&nonce=<?php echo esc_js( $nonce ); ?>','_blank')">
			↓ Export JSON
		</button>
		<label class="gt-btn gt-btn-ghost gt-btn-sm" style="cursor:pointer">
			↑ Import JSON
			<input type="file" accept=".json" style="display:none"
					onchange="gtCondImport(this,'<?php echo esc_js( $nonce ); ?>')">
		</label>
	</div>
</div>

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

<!-- ─── CONDITION PREVIEW ─────────────────────────────────────────────────── -->
<div class="gt-card gt-animate-in" style="margin-bottom:16px;border-color:rgba(59,130,246,0.2)">
	<div style="display:flex;align-items:flex-start;gap:14px">
		<span style="font-size:20px;flex-shrink:0;margin-top:2px">📋</span>
		<div style="flex:1">
			<div style="font-size:10px;font-weight:800;text-transform:uppercase;letter-spacing:.1em;color:#3b82f6;margin-bottom:6px">Plain-English Condition Summary</div>
			<div id="gt-cond-preview" style="font-size:13px;color:var(--gt-white);line-height:1.6">
				Loading condition preview…
			</div>
		</div>
		<div style="flex-shrink:0">
			<select id="gt-cond-template-sel"
					style="padding:7px 12px;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="">Quick Templates…</option>
				<?php foreach ( $templates as $i => $t ) : ?>
				<option value="<?php echo esc_attr( (string) $i ); ?>"><?php echo esc_html( $t[0] ); ?></option>
				<?php endforeach; ?>
			</select>
			<button type="button" class="gt-btn gt-btn-ghost gt-btn-sm" style="margin-top:4px;width:100%"
				onclick="gtCondApplyTemplate()">Apply Template</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>Advanced rule conditions require a PRO license.</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-cond-form" onchange="gtCondUpdatePreview()">
	<?php wp_nonce_field( 'gtbogo_conditions', 'gtbogo_conditions_nonce' ); ?>

<!-- AND / OR mode -->
<div class="gt-card gt-animate-in" style="margin-bottom:16px">
	<div class="gt-setting-row" style="border:none;padding:0">
		<div>
			<div class="gt-setting-label">Condition Mode</div>
			<div class="gt-setting-desc">
				<strong>ALL (AND)</strong> — every enabled condition must be satisfied simultaneously.<br>
				<strong>ANY (OR)</strong> — at least one enabled condition must be satisfied.
			</div>
		</div>
		<div style="display:flex;gap:6px">
			<label style="display:flex;align-items:center;gap:6px;padding:7px 14px;border:1px solid var(--gt-border-md);border-radius:7px;cursor:pointer;transition:all .15s;
							background:<?php echo ( $c['mode'] ?? 'all' ) === 'all' ? 'rgba(225,0,0,0.1)' : 'rgba(255,255,255,0.04)'; ?>">
				<input type="radio" name="condition_mode" value="all" id="gt-cond-mode-all"
						<?php checked( ( $c['mode'] ?? 'all' ) === 'all' ); ?>
						style="accent-color:var(--gt-red)"> ALL (AND)
			</label>
			<label style="display:flex;align-items:center;gap:6px;padding:7px 14px;border:1px solid var(--gt-border-md);border-radius:7px;cursor:pointer;
							background:<?php echo ( $c['mode'] ?? 'all' ) === 'any' ? 'rgba(225,0,0,0.1)' : 'rgba(255,255,255,0.04)'; ?>">
				<input type="radio" name="condition_mode" value="any" id="gt-cond-mode-any"
						<?php checked( ( $c['mode'] ?? 'all' ) === 'any' ); ?>
						style="accent-color:var(--gt-red)"> ANY (OR)
			</label>
		</div>
	</div>
</div>

<!-- ─── PRODUCT CONDITIONS ────────────────────────────────────────────────── -->
<div class="gt-card gt-animate-in" style="margin-bottom:16px">
	<div class="gt-card-header"><h2 class="gt-card-title">📦 Product Conditions</h2></div>
	<div style="display:grid;grid-template-columns:1fr 1fr;gap:16px">
		<!-- Categories -->
		<div>
			<div class="gt-form-label" style="margin-bottom:6px">
				Product Categories
				<?php if ( ! empty( $selected_cats ) ) : ?>
				<span style="margin-left:6px;background:var(--gt-red);color:#fff;font-size:9px;font-weight:800;padding:1px 6px;border-radius:20px"><?php echo count( $selected_cats ); ?></span>
				<?php endif; ?>
			</div>
			<input type="text" id="gt-cond-cat-search" placeholder="Search categories…"
					oninput="gtCondFilterTerms('cat')"
					style="padding:6px 10px;background:var(--gt-card);border:1px solid var(--gt-border-md);border-radius:6px;color:var(--gt-white);font-size:12px;width:100%;box-sizing:border-box;font-family:inherit;margin-bottom:8px">
			<div style="max-height:180px;overflow-y:auto;display:flex;flex-direction:column;gap:4px" id="gt-cond-cat-list">
			<?php
			if ( ! is_wp_error( $all_cats ) ) :
				foreach ( (array) $all_cats as $cat ) :
					$is_sel = in_array( (int) $cat->term_id, $selected_cats, true );
					?>
			<label class="gt-cond-cat-item" data-name="<?php echo esc_attr( strtolower( $cat->name ) ); ?>"
					style="display:flex;align-items:center;gap:8px;padding:5px 8px;border-radius:5px;cursor:pointer;
							background:<?php echo $is_sel ? 'rgba(225,0,0,0.07)' : 'rgba(255,255,255,0.02)'; ?>;
							border:1px solid <?php echo $is_sel ? 'rgba(225,0,0,0.2)' : 'var(--gt-border)'; ?>;font-size:12px;color:var(--gt-white)">
				<input type="checkbox" name="condition_categories[]"
						value="<?php echo esc_attr( (string) (int) $cat->term_id ); ?>"
						<?php checked( $is_sel ); ?> style="accent-color:var(--gt-red);flex-shrink:0">
				<span style="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)"><?php echo esc_html( (string) $cat->count ); ?></span>
			</label>
							<?php
							endforeach;
endif;
			?>
			</div>
		</div>

		<!-- Tags -->
		<div>
			<div class="gt-form-label" style="margin-bottom:6px">
				Product Tags
				<?php if ( ! empty( $selected_tags ) ) : ?>
				<span style="margin-left:6px;background:var(--gt-red);color:#fff;font-size:9px;font-weight:800;padding:1px 6px;border-radius:20px"><?php echo count( $selected_tags ); ?></span>
				<?php endif; ?>
			</div>
			<input type="text" id="gt-cond-tag-search" placeholder="Search tags…"
					oninput="gtCondFilterTerms('tag')"
					style="padding:6px 10px;background:var(--gt-card);border:1px solid var(--gt-border-md);border-radius:6px;color:var(--gt-white);font-size:12px;width:100%;box-sizing:border-box;font-family:inherit;margin-bottom:8px">
			<div style="max-height:180px;overflow-y:auto;display:flex;flex-direction:column;gap:4px" id="gt-cond-tag-list">
			<?php
			if ( ! is_wp_error( $all_tags ) ) :
				foreach ( array_slice( (array) $all_tags, 0, 60 ) as $tag ) :
					$is_sel = in_array( (int) $tag->term_id, $selected_tags, true );
					?>
			<label class="gt-cond-tag-item" data-name="<?php echo esc_attr( strtolower( $tag->name ) ); ?>"
					style="display:flex;align-items:center;gap:8px;padding:5px 8px;border-radius:5px;cursor:pointer;
							background:<?php echo $is_sel ? 'rgba(225,0,0,0.07)' : 'rgba(255,255,255,0.02)'; ?>;
							border:1px solid <?php echo $is_sel ? 'rgba(225,0,0,0.2)' : 'var(--gt-border)'; ?>;font-size:12px;color:var(--gt-white)">
				<input type="checkbox" name="condition_tags[]"
						value="<?php echo esc_attr( (string) (int) $tag->term_id ); ?>"
						<?php checked( $is_sel ); ?> style="accent-color:var(--gt-red);flex-shrink:0">
				<span style="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)"><?php echo esc_html( (string) $tag->count ); ?></span>
			</label>
							<?php
							endforeach;
endif;
			?>
			</div>
		</div>
	</div>

	<!-- Exclude sale toggle -->
	<div class="gt-setting-row" style="margin-top:14px;padding-top:14px;border-top:1px solid var(--gt-border)">
		<div>
			<div class="gt-setting-label">Exclude Sale-Priced Items</div>
			<div class="gt-setting-desc">BOGO rules never apply to products already on sale — prevents compounding discounts</div>
		</div>
		<label class="gt-toggle">
			<input type="checkbox" name="condition_exclude_sale" value="1"
					<?php checked( ! empty( $c['exclude_sale'] ) ); ?>>
			<span class="gt-toggle-track"><span class="gt-toggle-thumb"></span></span>
		</label>
	</div>
</div>

<!-- ─── CART VALUE ─────────────────────────────────────────────────────────── -->
<div class="gt-card gt-animate-in" style="margin-bottom:16px">
	<div class="gt-card-header"><h2 class="gt-card-title">💰 Cart Value Range</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" for="condition_min_cart">Minimum Cart Value ($)</label>
			<input type="number" name="condition_min_cart" id="condition_min_cart" class="gt-input"
					min="0" step="0.01"
					value="<?php echo esc_attr( (string) ( $c['min_cart'] ?? 0 ) ); ?>"
					oninput="gtCondUpdatePreview()">
			<div class="gt-form-hint">Rule only fires when cart subtotal is at or above this amount (0 = no minimum)</div>
		</div>
		<div class="gt-form-group" style="margin:0">
			<label class="gt-form-label" for="condition_max_cart">Maximum Cart Value ($)</label>
			<input type="number" name="condition_max_cart" id="condition_max_cart" class="gt-input"
					min="0" step="0.01"
					value="<?php echo esc_attr( (string) ( $c['max_cart'] ?? 0 ) ); ?>"
					oninput="gtCondUpdatePreview()">
			<div class="gt-form-hint">Rule stops firing above this cart value (0 = no maximum)</div>
		</div>
	</div>
</div>

<!-- ─── SCHEDULE ──────────────────────────────────────────────────────────── -->
<div class="gt-card gt-animate-in" style="margin-bottom:16px">
	<div class="gt-card-header"><h2 class="gt-card-title">📅 Schedule</h2></div>
	<div style="margin-bottom:14px">
		<div class="gt-form-label" style="margin-bottom:8px">Days of Week</div>
		<div style="display:flex;gap:6px;flex-wrap:wrap">
		<?php
		foreach ( $days_of_week as $dk => $dl ) :
			$is_sel = in_array( $dk, $selected_days, true );
			?>
		<label style="display:flex;align-items:center;gap:5px;padding:7px 14px;
						background:<?php echo $is_sel ? 'rgba(225,0,0,0.1)' : 'rgba(255,255,255,0.03)'; ?>;
						border:1px solid <?php echo $is_sel ? 'rgba(225,0,0,0.3)' : 'var(--gt-border)'; ?>;
						border-radius:7px;cursor:pointer;font-size:12px;font-weight:700;color:var(--gt-white)">
			<input type="checkbox" name="condition_days[]" value="<?php echo esc_attr( $dk ); ?>"
					<?php checked( $is_sel ); ?> style="accent-color:var(--gt-red)">
			<?php echo esc_html( $dl ); ?>
		</label>
		<?php endforeach; ?>
		</div>
	</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">Time Window Start</label>
			<input type="time" name="condition_time_start" class="gt-input"
					value="<?php echo esc_attr( $c['time_start'] ?? '00:00' ); ?>" oninput="gtCondUpdatePreview()">
			<div class="gt-form-hint">Server time (UTC)</div>
		</div>
		<div class="gt-form-group" style="margin:0">
			<label class="gt-form-label">Time Window End</label>
			<input type="time" name="condition_time_end" class="gt-input"
					value="<?php echo esc_attr( $c['time_end'] ?? '23:59' ); ?>" oninput="gtCondUpdatePreview()">
		</div>
	</div>
</div>

<!-- ─── ARCHETYPES ────────────────────────────────────────────────────────── -->
<div class="gt-card gt-animate-in" style="margin-bottom:16px">
	<div class="gt-card-header">
		<h2 class="gt-card-title">🧠 Customer Archetype Conditions</h2>
		<span style="font-size:12px;color:var(--gt-subtle)">Rule only fires for selected archetypes (empty = all archetypes)</span>
	</div>
	<div style="display:grid;grid-template-columns:repeat(4,1fr);gap:8px">
	<?php
	foreach ( $archetypes as $ak => $al ) :
		$is_sel = in_array( $ak, $selected_archetypes, true );
		?>
	<label style="display:flex;align-items:center;gap:7px;padding:8px 10px;
					background:<?php echo $is_sel ? 'rgba(225,0,0,0.07)' : 'rgba(255,255,255,0.02)'; ?>;
					border:1px solid <?php echo $is_sel ? 'rgba(225,0,0,0.2)' : 'var(--gt-border)'; ?>;
					border-radius:7px;cursor:pointer;font-size:12px;color:var(--gt-white)">
		<input type="checkbox" name="condition_archetypes[]" value="<?php echo esc_attr( $ak ); ?>"
				<?php checked( $is_sel ); ?> style="accent-color:var(--gt-red)">
		<?php echo esc_html( $al ); ?>
	</label>
	<?php endforeach; ?>
	</div>
</div>

<!-- ─── SIGNAL BUS THRESHOLDS ─────────────────────────────────────────────── -->
<div class="gt-card gt-animate-in" style="margin-bottom:16px">
	<div class="gt-card-header">
		<h2 class="gt-card-title">📡 Signal Bus Thresholds</h2>
		<span style="font-size:12px;color:var(--gt-subtle)">Rule only fires when signal value exceeds threshold (0 = disabled)</span>
	</div>
	<div style="display:grid;grid-template-columns:1fr 1fr;gap:10px">
	<?php
	foreach ( $signals as $sig_key => $sig_label ) :
		$thresh = (float) ( $signal_thresholds[ $sig_key ] ?? 0 );
		?>
	<div style="display:flex;align-items:center;gap:10px;padding:8px 0;border-bottom:1px solid rgba(255,255,255,0.03)">
		<div style="flex:1;font-size:12px;color:var(--gt-soft)"><?php echo esc_html( $sig_label ); ?></div>
		<input type="range" name="cond_signal[<?php echo esc_attr( $sig_key ); ?>]"
				min="0" max="5" step="0.5"
				value="<?php echo esc_attr( (string) $thresh ); ?>"
				oninput="this.nextElementSibling.textContent=parseFloat(this.value).toFixed(1)"
				style="width:80px;accent-color:var(--gt-red)">
		<div style="width:28px;text-align:right;font-size:11px;font-weight:700;color:var(--gt-subtle)">
			<?php echo esc_html( number_format( $thresh, 1 ) ); ?>
		</div>
	</div>
	<?php endforeach; ?>
	</div>
</div>

<!-- ─── GEO + SUBSCRIPTION ────────────────────────────────────────────────── -->
<div class="gt-animate-in" style="display:grid;grid-template-columns:1fr 1fr;gap:16px;margin-bottom:16px">
	<div class="gt-card">
		<div class="gt-card-header"><h2 class="gt-card-title">🌍 Geo Conditions</h2></div>
		<div class="gt-form-group" style="margin:0">
			<label class="gt-form-label">Country Codes (ISO 2-letter, comma-separated)</label>
			<input type="text" name="condition_geo[]" class="gt-input"
					value="<?php echo esc_attr( implode( ',', $selected_geo ) ); ?>"
					placeholder="US, CA, GB, AU">
			<div class="gt-form-hint">Leave blank for all countries. Uses WooCommerce billing country.</div>
		</div>
	</div>
	<div class="gt-card">
		<div class="gt-card-header"><h2 class="gt-card-title">🔄 Subscription Condition</h2></div>
		<div class="gt-setting-row" style="border:none;padding:0">
			<div>
				<div class="gt-setting-label">Require Active Subscription</div>
				<div class="gt-setting-desc">Rule only fires for customers with an active WC Subscription</div>
			</div>
			<label class="gt-toggle">
				<input type="checkbox" name="condition_require_sub" value="1"
						<?php checked( ! empty( $c['require_sub'] ) ); ?>>
				<span class="gt-toggle-track"><span class="gt-toggle-thumb"></span></span>
			</label>
		</div>
	</div>
</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 style="font-size:13px;color:var(--gt-subtle)">Conditions are evaluated in real time on every cart page load. Changes take effect immediately.</div>
		<button type="submit" name="gtbogo_save_conditions" class="gt-btn gt-btn-primary" style="padding:12px 32px">
			💾 Save Conditions
		</button>
	</div>
</div>

</form>
<?php endif; // is_pro ?>

<!-- ─── TEST RESULT ───────────────────────────────────────────────────────── -->
<div id="gt-cond-test-panel" 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">🔬 Live Cart Test Result</h2></div>
	<div id="gt-cond-test-content" style="font-size:13px;color:var(--gt-subtle)">Running…</div>
</div>

<script>
(function(){
'use strict';

/* ── Plain-English preview ───────────────────────────────────────────── */
function buildPreview() {
	var parts = [];
	var mode  = document.querySelector('[name=condition_mode]:checked')?.value || 'all';
	var min   = parseFloat(document.getElementById('condition_min_cart')?.value||0);
	var max   = parseFloat(document.getElementById('condition_max_cart')?.value||0);
	var ts    = document.querySelector('[name=condition_time_start]')?.value||'';
	var te    = document.querySelector('[name=condition_time_end]')?.value||'';
	var exSale= document.querySelector('[name=condition_exclude_sale]')?.checked;

	var selCats = Array.from(document.querySelectorAll('[name="condition_categories[]"]:checked')).map(function(el){return el.closest('label').querySelector('span').textContent.trim();});
	var selDays = Array.from(document.querySelectorAll('[name="condition_days[]"]:checked')).map(function(el){return el.value;});
	var selArch = Array.from(document.querySelectorAll('[name="condition_archetypes[]"]:checked')).map(function(el){return el.closest('label').textContent.trim();});

	if (selCats.length)   parts.push('products in: ' + selCats.slice(0,3).join(', ') + (selCats.length>3?' +more':''));
	if (selDays.length)   parts.push('on: ' + selDays.join(', '));
	if (ts && ts!=='00:00' || te && te!=='23:59') parts.push('between '+ts+' – '+te);
	if (min>0)  parts.push('cart ≥ $'+min.toFixed(2));
	if (max>0)  parts.push('cart ≤ $'+max.toFixed(2));
	if (exSale) parts.push('no sale items');
	if (selArch.length) parts.push('archetypes: '+selArch.slice(0,2).join(', ')+(selArch.length>2?' +more':''));

	var el = document.getElementById('gt-cond-preview');
	if (!el) return;
	if (!parts.length) {
		el.textContent = 'No conditions set — rules fire for ALL customers under ALL conditions.';
		el.style.color = 'var(--gt-subtle)';
	} else {
		el.textContent = 'Rule fires when ' + parts.join(' ' + mode.toUpperCase() + ' ') + '.';
		el.style.color = 'var(--gt-white)';
	}
}
window.gtCondUpdatePreview = buildPreview;
document.addEventListener('DOMContentLoaded', buildPreview);

/* ── Term search filter ──────────────────────────────────────────────── */
window.gtCondFilterTerms = function(type) {
	var q    = document.getElementById('gt-cond-'+type+'-search')?.value.toLowerCase()||'';
	var sel  = type==='cat' ? 'gt-cond-cat-item' : 'gt-cond-tag-item';
	document.querySelectorAll('.'+sel).forEach(function(el){
		el.style.display = el.getAttribute('data-name')?.includes(q) ? '' : 'none';
	});
};

/* ── Template presets ────────────────────────────────────────────────── */
var templates = <?php echo wp_json_encode( array_map( fn( $t )=>$t[1], $templates ) ); ?>;
window.gtCondApplyTemplate = function() {
	var sel = document.getElementById('gt-cond-template-sel');
	var idx = parseInt(sel?.value??'', 10);
	if (isNaN(idx) || !templates[idx]) return;
	var t = templates[idx];
	if (t.days) {
		document.querySelectorAll('[name="condition_days[]"]').forEach(function(cb){ cb.checked = t.days.includes(cb.value); });
	}
	if (t.min_cart !== undefined) { var mc = document.getElementById('condition_min_cart'); if(mc) mc.value = t.min_cart; }
	if (t.exclude_sale !== undefined) { var es = document.querySelector('[name=condition_exclude_sale]'); if(es) es.checked = t.exclude_sale; }
	if (t.archetypes) {
		document.querySelectorAll('[name="condition_archetypes[]"]').forEach(function(cb){ cb.checked = t.archetypes.includes(cb.value); });
	}
	if (t.time_start) { var ts = document.querySelector('[name=condition_time_start]'); if(ts) ts.value=t.time_start; }
	if (t.time_end)   { var te = document.querySelector('[name=condition_time_end]');   if(te) te.value=t.time_end; }
	buildPreview();
	if (sel) sel.value='';
};

/* ── Test live cart ──────────────────────────────────────────────────── */
window.gtCondTestCart = function(nonce) {
	var panel   = document.getElementById('gt-cond-test-panel');
	var content = document.getElementById('gt-cond-test-content');
	if (panel) panel.style.display = 'block';
	if (content) content.textContent = 'Evaluating current conditions against the live cart session…';

	var fd = new FormData();
	fd.append('action','gtbogo_cond_test_cart');
	fd.append('nonce', nonce);
	fetch(ajaxurl,{method:'POST',body:fd})
		.then(function(r){return r.json();})
		.then(function(resp){
			if (!content) return;
			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 State</div>' +
					'<div style="font-size:13px;color:var(--gt-white)">'+(d.cart_summary||'Cart empty')+'</div></div>' +
					'<div><div style="font-size:11px;color:var(--gt-subtle);margin-bottom:4px">Conditions Result</div>' +
					'<div style="font-size:16px;font-weight:700;color:'+(d.passes?'#22c55e':'#ef4444')+'">'+(d.passes?'✓ All conditions pass':'✗ Conditions not met')+'</div>' +
					'<div style="font-size:11px;color:var(--gt-subtle);margin-top:3px">'+(d.reason||'')+'</div></div></div>';
			} else {
				content.textContent = 'Test failed: '+(resp.data||'no session data available');
			}
		});
};

/* ── Import JSON ─────────────────────────────────────────────────────── */
window.gtCondImport = 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);
			var fd  = new FormData();
			fd.append('action','gtbogo_cond_import'); 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: '+err.message); }
	};
	reader.readAsText(file);
};

})();
</script>

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