<?php
// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals
// phpcs:disable WordPress.Security.NonceVerification
// phpcs:disable WordPress.Security.ValidatedSanitizedInput
// phpcs:disable WordPress.WP.EnqueuedResourceParameters
// phpcs:disable WordPress.DB.PreparedSQL
// phpcs:disable WordPress.DB.PreparedSQLPlaceholders
// phpcs:disable WordPress.DB.DirectDatabaseQuery
// phpcs:disable WordPress.DB.SlowDBQuery
// phpcs:disable PluginCheck.Security.DirectDB
// phpcs:disable PluginCheck.CodeAnalysis
// phpcs:disable WordPressVIPMinimum

/**
 * GT BOGO Engine — A/B Testing (Enterprise)
 *
 * @package GT_BOGO_Engine
 * @since   3.11.0
 */
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
if ( ! current_user_can( 'manage_options' ) ) {
	return;
}

$is_pro       = function_exists( 'gt_bogo_has_pro' ) ? gt_bogo_has_pro() : false;
$message      = '';
$message_type = '';
global $wpdb;
$rtbl  = $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $wpdb->prefix . 'gtbogo_rules' ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.DirectDatabaseQuery.SchemaChange,WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.PreparedSQL.NotPrepared,PluginCheck.Security.DirectDB.UnescapedDBParameter,WordPress.DB.PreparedSQLPlaceholders.UnnecessaryPrepare
$rules = $rtbl ? $wpdb->get_results( "SELECT id, name, status FROM {$wpdb->prefix}gtbogo_rules ORDER BY name ASC" ) : array(); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.DirectDatabaseQuery.SchemaChange,WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.PreparedSQL.NotPrepared,PluginCheck.Security.DirectDB.UnescapedDBParameter,WordPress.DB.PreparedSQLPlaceholders.UnnecessaryPrepare
$atbl  = $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $wpdb->prefix . 'gtbogo_analytics' ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.DirectDatabaseQuery.SchemaChange,WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.PreparedSQL.NotPrepared,PluginCheck.Security.DirectDB.UnescapedDBParameter,WordPress.DB.PreparedSQLPlaceholders.UnnecessaryPrepare

// ── Save Test ─────────────────────────────────────────────────────────────
if ( $is_pro && isset( $_POST['gtbogo_save_abtest'] ) && check_admin_referer( 'gtbogo_save_abtest' ) ) {
	$tests         = get_option( 'gtbogo_abtests', array() );
	$tid           = sanitize_text_field( $_POST['test_id'] ?? uniqid( 'ab_' ) );
	$tests[ $tid ] = array(
		'name'       => sanitize_text_field( $_POST['test_name'] ?? 'New Test' ),
		'hypothesis' => sanitize_textarea_field( $_POST['test_hypo'] ?? '' ),
		'rule_a'     => intval( $_POST['test_rule_a'] ?? 0 ),
		'rule_b'     => intval( $_POST['test_rule_b'] ?? 0 ),
		'split'      => intval( $_POST['test_split'] ?? 50 ),
		'metric'     => sanitize_text_field( $_POST['test_metric'] ?? 'orders' ),
		'start_date' => sanitize_text_field( $_POST['test_start'] ?? '' ),
		'end_date'   => sanitize_text_field( $_POST['test_end'] ?? '' ),
		'status'     => sanitize_text_field( $_POST['test_status'] ?? 'draft' ),
		'winner'     => sanitize_text_field( $_POST['test_winner'] ?? '' ),
		'conclusion' => sanitize_textarea_field( $_POST['test_conclusion'] ?? '' ),
		'created'    => $tests[ $tid ]['created'] ?? current_time( 'mysql', true ),
		'updated'    => current_time( 'mysql', true ),
	);
	update_option( 'gtbogo_abtests', $tests );
	if ( function_exists( 'gt_bogo_log' ) ) {
		gt_bogo_log( 'A/B test saved', $tests[ $tid ]['name'] . ' (Status: ' . $tests[ $tid ]['status'] . ')', 'success' );
	}
	$message      = 'A/B test saved.';
	$message_type = 'success';
}

// ── Conclude Test ─────────────────────────────────────────────────────────
if ( $is_pro && isset( $_POST['gtbogo_conclude_test'] ) && check_admin_referer( 'gtbogo_conclude_' . intval( $_POST['conclude_id'] ?? 0 ) ) ) {
	$tests = get_option( 'gtbogo_abtests', array() );
	$tid   = sanitize_text_field( $_POST['conclude_id'] ?? '' );
	if ( isset( $tests[ $tid ] ) ) {
		$tests[ $tid ]['status']       = 'concluded';
		$tests[ $tid ]['winner']       = sanitize_text_field( $_POST['winner'] ?? '' );
		$tests[ $tid ]['conclusion']   = sanitize_textarea_field( $_POST['conclusion'] ?? '' );
		$tests[ $tid ]['concluded_at'] = current_time( 'mysql', true );
		update_option( 'gtbogo_abtests', $tests );
		if ( function_exists( 'gt_bogo_log' ) ) {
			gt_bogo_log( 'A/B test concluded', $tests[ $tid ]['name'] . ' Winner: ' . $tests[ $tid ]['winner'], 'success' );
		}
		$message      = 'Test concluded and winner recorded.';
		$message_type = 'success';
	}
}

// ── Delete Test ───────────────────────────────────────────────────────────
if ( $is_pro && isset( $_GET['del_ab'] ) && check_admin_referer( 'del_ab_' . sanitize_text_field( $_GET['del_ab'] ) ) ) {
	$tests = get_option( 'gtbogo_abtests', array() );
	$tid   = sanitize_text_field( $_GET['del_ab'] );
	if ( function_exists( 'gt_bogo_log' ) && isset( $tests[ $tid ] ) ) {
		gt_bogo_log( 'A/B test deleted', $tests[ $tid ]['name'], 'warn' );
	}
	unset( $tests[ $tid ] );
	update_option( 'gtbogo_abtests', $tests );
	$message      = 'Test deleted.';
	$message_type = 'success';
}

$tests        = get_option( 'gtbogo_abtests', array() );
$active_tests = count( array_filter( $tests, fn( $t )=>$t['status'] === 'running' ) );
$edit_tid     = isset( $_GET['edit_ab'] ) ? sanitize_text_field( $_GET['edit_ab'] ) : '';
$edit_test    = ( $edit_tid && isset( $tests[ $edit_tid ] ) ) ? $tests[ $edit_tid ] : null;

// Pull rule analytics for test comparison
function gt_ab_rule_stats( $wpdb, $atbl, $rule_id, $start, $end ) {
	if ( ! $atbl || ! $rule_id ) {
		return array(
			'orders'    => 0,
			'revenue'   => 0,
			'discounts' => 0,
			'aov'       => 0,
		);
	}
	// Analytics table stores rule_id — join on rule_id, not rule_name
	$q    = "SELECT COUNT(DISTINCT order_id) AS orders, COALESCE(SUM(order_total),0) AS revenue,
                 COALESCE(SUM(discount_amount),0) AS discounts, COALESCE(AVG(order_total),0) AS aov
          FROM {$atbl} WHERE rule_id=%d";
	$args = array( (int) $rule_id );
	if ( $start ) {
		$q     .= ' AND date_created>=%s';
		$args[] = $start . ' 00:00:00'; }
	if ( $end ) {
		$q     .= ' AND date_created<=%s';
		$args[] = $end . ' 23:59:59'; }
	return (array) ( $wpdb->get_row( $wpdb->prepare( $q, $args ), ARRAY_A ) ?? array(
		'orders'    => 0,
		'revenue'   => 0,
		'discounts' => 0,
		'aov'       => 0,
	) ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared,WordPress.DB.PreparedSQLPlaceholders.UnescapedDBParameter
}

require_once __DIR__ . '/../ui-system/wrapper-start.php';
?>
<div class="gt-page-header gt-animate-in">
	<div>
		<h1 class="gt-page-title">🧪 A/B Testing</h1>
		<p class="gt-page-subtitle">Run structured experiments comparing two BOGO rules — log hypotheses, track results, and record winners</p>
	</div>
	<div style="display:flex;gap:8px;align-items:center">
		<span class="gt-badge gt-badge-active"><?php echo esc_html( count( $tests ) ); ?> Test<?php echo count( $tests ) !== 1 ? 's' : ''; ?></span>
		<?php
		if ( $active_tests ) :
			?>
			<span class="gt-badge gt-badge-warn">● <?php echo esc_html( $active_tests ); ?> Running</span><?php endif; ?>
	</div>
</div>
<?php
if ( $message ) :
	?>
	<div class="gt-notice gt-notice-<?php echo esc_attr( $message_type ); ?> gt-animate-in">✓ <?php echo esc_html( $message ); ?></div><?php endif; ?>

<?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>A/B Testing gives you a structured framework to compare BOGO rules — log hypotheses, track real analytics side-by-side, and record what works for continuous improvement.</p>
	<div style="display:grid;grid-template-columns:repeat(2,1fr);gap:12px;max-width:480px;margin:24px auto 0">
		<?php foreach ( array( 'Compare any two rules with traffic splitting', 'Live analytics comparison from real order data', 'Hypothesis and conclusion logging', 'Winner recording for institutional knowledge' ) as $f ) : ?>
		<div style="display:flex;align-items:flex-start;gap:8px;text-align:left"><span style="color:#e10000;font-weight:700">—</span><span style="font-size:13px;color:var(--gt-soft)"><?php echo esc_html( $f ); ?></span></div>
		<?php endforeach; ?>
	</div>
	<div style="margin-top:24px;display:flex;justify-content:center;gap:12px">
		<a href="https://graphictshirts.shop/bogo/" target="_blank" rel="noopener" class="gt-btn gt-btn-primary">Purchase PRO — $499/yr</a>
	</div>
</div>
<?php else : ?>

<!-- METRICS -->
<div class="gt-metrics gt-animate-in" style="margin-bottom:20px">
	<?php
	$concluded = count( array_filter( $tests, fn( $t )=>$t['status'] === 'concluded' ) );
	$draft     = count( array_filter( $tests, fn( $t )=>$t['status'] === 'draft' ) );
	?>
	<div class="gt-metric" style="--gt-metric-c:#e10000"><span class="gt-metric-icon">🧪</span><div class="gt-metric-label">Total Tests</div><div class="gt-metric-value"><?php echo esc_html( count( $tests ) ); ?></div><div class="gt-metric-trend"><?php echo esc_html( $draft ); ?> draft · <?php echo esc_html( $active_tests ); ?> running · <?php echo esc_html( $concluded ); ?> concluded</div></div>
	<div class="gt-metric" style="--gt-metric-c:#22c55e"><span class="gt-metric-icon">✅</span><div class="gt-metric-label">Concluded</div><div class="gt-metric-value"><?php echo esc_html( $concluded ); ?></div><div class="gt-metric-trend">With recorded winner</div></div>
	<div class="gt-metric" style="--gt-metric-c:#f59e0b"><span class="gt-metric-icon">▶</span><div class="gt-metric-label">Running Now</div><div class="gt-metric-value"><?php echo esc_html( $active_tests ); ?></div><div class="gt-metric-trend">Live experiments</div></div>
	<div class="gt-metric" style="--gt-metric-c:#3b82f6"><span class="gt-metric-icon">📋</span><div class="gt-metric-label">Rules Available</div><div class="gt-metric-value"><?php echo esc_html( count( $rules ) ); ?></div><div class="gt-metric-trend">For test variants</div></div>
</div>

<!-- TEST LIST -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
	<div class="gt-card-header">
		<h2 class="gt-card-title">🧪 Experiments</h2>
		<a href="?page=gt-bogo-engine&tab=ab-testing&new_ab=1" class="gt-btn gt-btn-primary gt-btn-sm">+ New Test</a>
	</div>
	<?php if ( ! empty( $tests ) ) : ?>
	<div style="display:flex;flex-direction:column;gap:12px">
		<?php
		foreach ( $tests as $tid => $test ) :
			$status_colors = array(
				'draft'     => '#94a3b8',
				'running'   => '#86efac',
				'concluded' => '#93c5fd',
			);
			$st_color      = $status_colors[ $test['status'] ] ?? '#94a3b8';
			$rule_a        = null;
			$rule_b        = null;
			foreach ( $rules as $r ) {
				if ( $r->id == $test['rule_a'] ) {
					$rule_a = $r;
				} if ( $r->id == $test['rule_b'] ) {
					$rule_b = $r;
				}
			}
			// Pull stats if running or concluded
			$stats_a = array(
				'orders'  => '—',
				'revenue' => '—',
			);
			$stats_b = array(
				'orders'  => '—',
				'revenue' => '—',
			);
			if ( $test['status'] !== 'draft' && $atbl ) {
				$atbl_full = $wpdb->prefix . 'gtbogo_analytics';
				$sa        = gt_ab_rule_stats( $wpdb, $atbl_full, $test['rule_a'], $test['start_date'], $test['status'] === 'concluded' ? ( $test['end_date'] ?? '' ) : '' );
				$sb        = gt_ab_rule_stats( $wpdb, $atbl_full, $test['rule_b'], $test['start_date'], $test['status'] === 'concluded' ? ( $test['end_date'] ?? '' ) : '' );
				$stats_a   = array(
					'orders'  => number_format( $sa['orders'] ),
					'revenue' => '$' . number_format( $sa['revenue'], 2 ),
					'aov'     => '$' . number_format( $sa['aov'], 2 ),
				);
				$stats_b   = array(
					'orders'  => number_format( $sb['orders'] ),
					'revenue' => '$' . number_format( $sb['revenue'], 2 ),
					'aov'     => '$' . number_format( $sb['aov'], 2 ),
				);
			}
			?>
		<div style="border:1px solid <?php echo $test['status'] === 'running' ? 'rgba(34,197,94,0.3)' : 'var(--gt-border)'; ?>;border-radius:12px;overflow:hidden">
			<!-- Header -->
			<div style="padding:14px 20px;background:rgba(255,255,255,0.02);display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:12px">
				<div>
					<div style="display:flex;align-items:center;gap:10px;margin-bottom:4px">
						<span style="font-size:14px;font-weight:800;color:var(--gt-white)"><?php echo esc_html( $test['name'] ); ?></span>
						<span style="font-size:13px;font-weight:700;color:<?php echo esc_html( $st_color ); ?>;background:rgba(255,255,255,0.04);padding:2px 10px;border-radius:50px;border:1px solid <?php echo esc_html( $st_color ); ?>30"><?php echo esc_html( strtoupper( $test['status'] ) ); ?></span>
						<?php
						if ( $test['winner'] ) :
							?>
							<span style="font-size:13px;color:#fcd34d;font-weight:700">🏆 Winner: <?php echo esc_html( $test['winner'] ); ?></span><?php endif; ?>
					</div>
					<?php
					if ( $test['hypothesis'] ) :
						?>
						<div style="font-size:13px;color:var(--gt-soft);font-style:italic"><?php echo esc_html( $test['hypothesis'] ); ?></div><?php endif; ?>
					<div style="font-size:13px;color:var(--gt-subtle);margin-top:3px">
						<?php
						if ( $test['start_date'] ) :
							?>
							📅 <?php echo esc_html( $test['start_date'] ); ?>
							<?php
							if ( $test['end_date'] ) :
								?>
							→ <?php echo esc_html( $test['end_date'] ); ?><?php endif; ?><?php endif; ?>
						· Split: <?php echo esc_html( $test['split'] ); ?>% / <?php echo 100 - intval( $test['split'] ); ?>%
						· Primary metric: <?php echo esc_html( $test['metric'] ); ?>
					</div>
				</div>
				<div style="display:flex;gap:8px">
					<a href="?page=gt-bogo-engine&tab=ab-testing&edit_ab=<?php echo esc_attr( $tid ); ?>" class="gt-btn gt-btn-ghost gt-btn-sm">✎ Edit</a>
					<a href="
					<?php
					echo esc_url(
						wp_nonce_url(
							add_query_arg(
								array(
									'del_ab' => $tid,
									'page'   => 'gt-bogo-engine',
									'tab'    => 'ab-testing',
								),
								admin_url( 'admin.php' )
							),
							'del_ab_' . $tid
						)
					);
					?>
								" class="gt-btn gt-btn-ghost gt-btn-sm" style="color:#fca5a5" onclick="return confirm('Delete this test?')">✕</a>
				</div>
			</div>
			<!-- Side-by-side comparison -->
			<div style="display:grid;grid-template-columns:1fr 1fr;border-top:1px solid var(--gt-border)">
				<?php foreach ( array( array( 'A', $rule_a, $stats_a, $test['rule_a'] ), array( 'B', $rule_b, $stats_b, $test['rule_b'] ) ) as $v ) : ?>
				<div style="padding:16px 20px;<?php echo $v[0] === 'A' ? 'border-right:1px solid var(--gt-border)' : ''; ?>">
					<div style="font-size:13px;font-weight:800;color:var(--gt-subtle);text-transform:uppercase;letter-spacing:1px;margin-bottom:6px">Variant <?php echo esc_html( $v[0] ); ?>
					<?php
					if ( $test['winner'] === $v[0] ) :
						?>
						🏆<?php endif; ?></div>
					<div style="font-size:14px;font-weight:700;color:var(--gt-white);margin-bottom:10px"><?php echo esc_html( $v[1] ) ? esc_html( $v[1]->name ) : '<span style="color:var(--gt-subtle)">Rule not set</span>'; ?></div>
					<?php if ( $test['status'] !== 'draft' ) : ?>
					<div style="display:grid;grid-template-columns:repeat(3,1fr);gap:8px">
						<?php
						foreach ( array(
							'orders'  => 'Orders',
							'revenue' => 'Revenue',
							'aov'     => 'AOV',
						) as $k => $l ) :
							?>
						<div style="text-align:center;padding:10px;background:rgba(255,255,255,0.02);border-radius:8px;border:1px solid var(--gt-border)">
							<div style="font-size:13px;color:var(--gt-subtle);margin-bottom:3px"><?php echo esc_html( $l ); ?></div>
							<div style="font-size:14px;font-weight:700;color:var(--gt-white)"><?php echo esc_html( $v[2][ $k ] ?? '—' ); ?></div>
						</div>
						<?php endforeach; ?>
					</div>
					<?php endif; ?>
				</div>
				<?php endforeach; ?>
			</div>
			<!-- Conclude -->
			<?php if ( $test['status'] === 'running' ) : ?>
			<div style="padding:12px 20px;border-top:1px solid var(--gt-border);background:rgba(255,255,255,0.01)">
				<form method="post" action="" style="display:flex;gap:12px;align-items:center;flex-wrap:wrap">
					<?php wp_nonce_field( 'gtbogo_conclude_' . $tid ); ?>
					<input type="hidden" name="conclude_id" value="<?php echo esc_attr( $tid ); ?>">
					<select name="winner" class="gt-select gt-btn-sm" style="width:120px">
						<option value="">— Pick winner —</option>
						<option value="A">Variant A wins</option>
						<option value="B">Variant B wins</option>
						<option value="inconclusive">Inconclusive</option>
					</select>
					<input type="text" name="conclusion" class="gt-input gt-btn-sm" style="flex:1;min-width:200px" placeholder="Conclusion notes..." id="gtbogo_conclusion" aria-label="Conclusion">
					<button type="submit" name="gtbogo_conclude_test" class="gt-btn gt-btn-primary gt-btn-sm">🏁 Conclude Test</button>
				</form>
			</div>
			<?php endif; ?>
			<?php if ( ! empty( $test['conclusion'] ) ) : ?>
			<div style="padding:10px 20px;border-top:1px solid var(--gt-border);font-size:13px;color:var(--gt-soft);font-style:italic">📝 <?php echo esc_html( $test['conclusion'] ); ?></div>
			<?php endif; ?>
		</div>
		<?php endforeach; ?>
	</div>
	<?php else : ?>
	<div style="text-align:center;padding:48px 24px">
		<div style="font-size:48px;margin-bottom:16px">🧪</div>
		<h3 style="color:var(--gt-white);margin:0 0 8px">No Tests Yet</h3>
		<p class="gt-text-soft" style="font-size:13px">Create your first A/B test to start comparing rule performance scientifically.</p>
		<a href="?page=gt-bogo-engine&tab=ab-testing&new_ab=1" class="gt-btn gt-btn-primary gt-btn-sm" style="margin-top:16px">+ Create First Test</a>
	</div>
	<?php endif; ?>
</div>

<!-- TEST FORM -->
	<?php if ( isset( $_GET['new_ab'] ) || $edit_test ) : ?>
<div class="gt-card gt-animate-in" style="margin-bottom:20px;border-color:rgba(225,0,0,0.2)">
	<div class="gt-card-header">
		<h2 class="gt-card-title"><?php echo esc_html( $edit_test ) ? '✎ Edit: ' . esc_html( $edit_test['name'] ) : '➕ New A/B Test'; ?></h2>
		<a href="?page=gt-bogo-engine&tab=ab-testing" class="gt-btn gt-btn-ghost gt-btn-sm">✕ Cancel</a>
	</div>
	<form method="post" action="">
		<?php wp_nonce_field( 'gtbogo_save_abtest' ); ?>
		<?php
		if ( $edit_test ) :
			?>
			<input type="hidden" name="test_id" value="<?php echo esc_attr( $edit_tid ); ?>"><?php endif; ?>

		<div style="display:grid;grid-template-columns:1fr 1fr;gap:20px;margin-bottom:20px">
			<div class="gt-form-group">
				<label class="gt-form-label">Test Name</label>
				<input type="text" name="test_name" class="gt-input" value="<?php echo esc_attr( $edit_test['name'] ?? '' ); ?>" placeholder="e.g. BOGO 100% vs BOGO 50%" required id="gtbogo_test_name" aria-label="Test Name">
			</div>
			<div class="gt-form-group">
				<label class="gt-form-label">Status</label>
				<select name="test_status" class="gt-select">
					<option value="draft"     <?php selected( $edit_test['status'] ?? 'draft', 'draft' ); ?>>Draft</option>
					<option value="running"   <?php selected( $edit_test['status'] ?? '', 'running' ); ?>>Running</option>
					<option value="paused"    <?php selected( $edit_test['status'] ?? '', 'paused' ); ?>>Paused</option>
					<option value="concluded" <?php selected( $edit_test['status'] ?? '', 'concluded' ); ?>>Concluded</option>
				</select>
			</div>
		</div>
		<div class="gt-form-group">
			<label class="gt-form-label">Hypothesis</label>
			<textarea name="test_hypo" class="gt-input" rows="2" placeholder="e.g. We believe BOGO 50% will drive higher order volume than BOGO 100% because the margin savings will let us promote it more aggressively."><?php echo esc_textarea( $edit_test['hypothesis'] ?? '' ); ?></textarea>
		</div>
		<div style="display:grid;grid-template-columns:1fr 1fr;gap:20px;margin-bottom:20px">
			<div class="gt-form-group">
				<label class="gt-form-label">Variant A Rule</label>
				<select name="test_rule_a" class="gt-select">
					<option value="0">— Select rule —</option>
					<?php
					foreach ( $rules as $rule ) :
						?>
						<option value="<?php echo esc_html( $rule->id ); ?>" <?php selected( $edit_test['rule_a'] ?? 0, $rule->id ); ?>><?php echo esc_html( $rule->name ); ?></option><?php endforeach; ?>
				</select>
			</div>
			<div class="gt-form-group">
				<label class="gt-form-label">Variant B Rule</label>
				<select name="test_rule_b" class="gt-select">
					<option value="0">— Select rule —</option>
					<?php
					foreach ( $rules as $rule ) :
						?>
						<option value="<?php echo esc_html( $rule->id ); ?>" <?php selected( $edit_test['rule_b'] ?? 0, $rule->id ); ?>><?php echo esc_html( $rule->name ); ?></option><?php endforeach; ?>
				</select>
			</div>
		</div>
		<div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:16px;margin-bottom:20px">
			<div class="gt-form-group">
				<label class="gt-form-label">Traffic Split (% to Variant A)</label>
				<input type="number" name="test_split" class="gt-input" value="<?php echo esc_attr( $edit_test['split'] ?? 50 ); ?>" min="10" max="90" id="gtbogo_test_split" aria-label="Test Split">
				<div class="gt-form-hint">50 = equal split. 70 = 70% see A, 30% see B.</div>
			</div>
			<div class="gt-form-group">
				<label class="gt-form-label">Primary Metric</label>
				<select name="test_metric" class="gt-select">
					<option value="orders"   <?php selected( $edit_test['metric'] ?? 'orders', 'orders' ); ?>>Order Volume</option>
					<option value="revenue"  <?php selected( $edit_test['metric'] ?? '', 'revenue' ); ?>>Revenue</option>
					<option value="aov"      <?php selected( $edit_test['metric'] ?? '', 'aov' ); ?>>Average Order Value</option>
					<option value="discount" <?php selected( $edit_test['metric'] ?? '', 'discount' ); ?>>Discount Cost</option>
				</select>
			</div>
			<div class="gt-form-group">
				<label class="gt-form-label">Start Date</label>
				<input type="date" name="test_start" class="gt-input" value="<?php echo esc_attr( $edit_test['start_date'] ?? '' ); ?>" id="gtbogo_test_start" aria-label="Test Start">
			</div>
		</div>
		<div class="gt-form-group">
			<label class="gt-form-label">End Date</label>
			<input type="date" name="test_end" class="gt-input" style="max-width:200px" value="<?php echo esc_attr( $edit_test['end_date'] ?? '' ); ?>" id="gtbogo_test_end" aria-label="Test End">
			<div class="gt-form-hint">Leave blank for open-ended. Conclude manually when ready.</div>
		</div>
		<div style="display:flex;gap:12px;justify-content:flex-end;margin-top:8px">
			<a href="?page=gt-bogo-engine&tab=ab-testing" class="gt-btn gt-btn-ghost">Cancel</a>
			<button type="submit" name="gtbogo_save_abtest" class="gt-btn gt-btn-primary" style="padding:12px 32px">💾 Save Test</button>
		</div>
	</form>
</div>
	<?php endif; ?>

<!-- GUIDANCE -->
<div class="gt-card gt-animate-in" style="background:linear-gradient(135deg,rgba(59,130,246,0.06),rgba(7,12,28,0));border-color:rgba(59,130,246,0.15)">
	<div class="gt-card-header"><h2 class="gt-card-title">🧠 A/B Testing Best Practices</h2></div>
	<div class="gt-feature-grid gt-feature-grid--2col">
		<div><div style="font-size:13px;font-weight:700;color:var(--gt-white);margin-bottom:6px">Change One Variable at a Time</div><div style="font-size:13px;color:var(--gt-soft);line-height:1.7">A valid A/B test changes exactly one thing between variants. Compare BOGO 100% vs BOGO 50%. Do not compare BOGO 100% with a minimum cart vs BOGO 50% without one — you will not know which variable drove the difference.</div></div>
		<div><div style="font-size:13px;font-weight:700;color:var(--gt-white);margin-bottom:6px">Run for at Least 14 Days</div><div style="font-size:13px;color:var(--gt-soft);line-height:1.7">Weekday vs weekend shopping behaviour is dramatically different for most stores. Running a test for less than two full weeks risks picking a winner that is actually a weekend outlier. Aim for 21–30 days for tests covering campaign periods with irregular traffic.</div></div>
		<div><div style="font-size:13px;font-weight:700;color:var(--gt-white);margin-bottom:6px">Traffic Split Strategy</div><div style="font-size:13px;color:var(--gt-soft);line-height:1.7">Start with a 70/30 split rather than 50/50. Give 70% of traffic to your current best-performing rule and 30% to the challenger. If the challenger fails, your impact is limited. Once you have signal, rebalance to 50/50 for a cleaner final read.</div></div>
		<div><div style="font-size:13px;font-weight:700;color:var(--gt-white);margin-bottom:6px">Always Write a Hypothesis First</div><div style="font-size:13px;color:var(--gt-soft);line-height:1.7">The hypothesis field is not optional — it forces you to articulate why you expect one variant to win before you see the data. This prevents post-hoc rationalisation where you explain a random result as if you predicted it, which leads to false confidence in inconclusive tests.</div></div>
	</div>
</div>

<?php endif; ?>
<script>
(function(){
	// Live A/B test results polling
	function refreshABResults() {
		var cards = document.querySelectorAll('.gt-ab-results-card');
		cards.forEach(function(card) {
			var tid = card.dataset.tid;
			if (!tid) return;
			var fd = new FormData();
			fd.append('action', 'gtbogo_ab_live_results');
			fd.append('nonce', gtBogoAdmin.nonce);
			fd.append('test_id', tid);
			fetch(ajaxurl, {method:'POST', body:fd, credentials:'same-origin'})
				.then(r => r.json())
				.then(d => {
					if (!d.success) return;
					var data = d.data;
					// Update impressions and conversions
					var elA = card.querySelector('.gt-ab-impressions-a');
					var elB = card.querySelector('.gt-ab-impressions-b');
					var cvA = card.querySelector('.gt-ab-conv-a');
					var cvB = card.querySelector('.gt-ab-conv-b');
					if (elA) elA.textContent = data.rule_a_impressions || 0;
					if (elB) elB.textContent = data.rule_b_impressions || 0;
					if (cvA) cvA.textContent = (data.rule_a_rate || 0) + '%';
					if (cvB) cvB.textContent = (data.rule_b_rate || 0) + '%';
					// Highlight winner
					if (data.leader) {
						var winner = card.querySelector('.gt-ab-winner-' + data.leader);
						if (winner) winner.style.borderColor = '#22c55e';
					}
				});
		});
	}
	// Poll every 30s on active tests
	if (document.querySelector('.gt-ab-results-card')) {
		refreshABResults();
		setInterval(refreshABResults, 30000);
	}
	// Conclude test confirmation
	document.querySelectorAll('.gt-ab-conclude-btn').forEach(function(btn) {
		btn.addEventListener('click', function(e) {
			if (!confirm('Mark this test as concluded? This cannot be undone.')) e.preventDefault();
		});
	});
})();
</script>

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