<?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 — Customer Segments (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

// ── Save Segment ──────────────────────────────────────────────────────────
if ( $is_pro && isset( $_POST['gtbogo_save_segment'] ) && check_admin_referer( 'gtbogo_save_segment' ) ) {
	$segments            = get_option( 'gtbogo_segments', array() );
	$seg_id              = sanitize_text_field( $_POST['segment_id'] ?? uniqid( 'seg_' ) );
	$segments[ $seg_id ] = array(
		'name'        => sanitize_text_field( $_POST['seg_name'] ?? 'New Segment' ),
		'description' => sanitize_textarea_field( $_POST['seg_desc'] ?? '' ),
		'conditions'  => array(
			'roles'            => array_map( 'sanitize_text_field', (array) ( $_POST['seg_roles'] ?? array() ) ),
			'min_orders'       => intval( $_POST['seg_min_orders'] ?? 0 ),
			'max_orders'       => intval( $_POST['seg_max_orders'] ?? 0 ),
			'min_spend'        => floatval( $_POST['seg_min_spend'] ?? 0 ),
			'max_spend'        => floatval( $_POST['seg_max_spend'] ?? 0 ),
			'days_since_last'  => intval( $_POST['seg_days_since_last'] ?? 0 ),
			'days_since_first' => intval( $_POST['seg_days_since_first'] ?? 0 ),
			'registered_after' => sanitize_text_field( $_POST['seg_reg_after'] ?? '' ),
			'has_category'     => array_map( 'intval', (array) ( $_POST['seg_has_cat'] ?? array() ) ),
			'coupon_used'      => isset( $_POST['seg_coupon_used'] ),
			'email_domain'     => sanitize_text_field( $_POST['seg_email_domain'] ?? '' ),
		),
		'rule_ids'    => array_map( 'intval', (array) ( $_POST['seg_rule_ids'] ?? array() ) ),
		'mode'        => sanitize_text_field( $_POST['seg_mode'] ?? 'include' ),
		'enabled'     => isset( $_POST['seg_enabled'] ),
		'created'     => $segments[ $seg_id ]['created'] ?? current_time( 'mysql', true ),
		'updated'     => current_time( 'mysql', true ),
	);
	update_option( 'gtbogo_segments', $segments );
	if ( function_exists( 'gt_bogo_log' ) ) {
		gt_bogo_log( 'Segment saved', $segments[ $seg_id ]['name'], 'success' );
	}
	delete_transient( 'gtbogo_active_rules' );
	delete_transient( 'gtbogo_active_rules_summary' );
	$message      = 'Segment saved.';
	$message_type = 'success';
}

// ── Delete Segment ────────────────────────────────────────────────────────
if ( $is_pro && isset( $_GET['del_seg'] ) && check_admin_referer( 'del_seg_' . sanitize_text_field( $_GET['del_seg'] ) ) ) {
	$segments = get_option( 'gtbogo_segments', array() );
	$sid      = sanitize_text_field( $_GET['del_seg'] );
	if ( function_exists( 'gt_bogo_log' ) && isset( $segments[ $sid ] ) ) {
		gt_bogo_log( 'Segment deleted', $segments[ $sid ]['name'], 'warn' );
	}
	unset( $segments[ $sid ] );
	update_option( 'gtbogo_segments', $segments );
	$message      = 'Segment deleted.';
	$message_type = 'success';
}

// ── Toggle Segment ────────────────────────────────────────────────────────
if ( $is_pro && isset( $_GET['toggle_seg'] ) && check_admin_referer( 'toggle_seg_' . sanitize_text_field( $_GET['toggle_seg'] ) ) ) {
	$segments = get_option( 'gtbogo_segments', array() );
	$sid      = sanitize_text_field( $_GET['toggle_seg'] );
	if ( isset( $segments[ $sid ] ) ) {
		$segments[ $sid ]['enabled'] = ! ( $segments[ $sid ]['enabled'] ?? true );
		update_option( 'gtbogo_segments', $segments );
		delete_transient( 'gtbogo_active_rules' );
		delete_transient( 'gtbogo_active_rules_summary' );
		$message      = 'Segment ' . ( $segments[ $sid ]['enabled'] ? 'enabled' : 'disabled' ) . '.';
		$message_type = 'success';
	}
}

$segments    = get_option( 'gtbogo_segments', array() );
$active_segs = count( array_filter( $segments, fn( $s ) => ! empty( $s['enabled'] ) ) );
$wp_roles    = wp_roles()->get_names();
$categories  = get_terms(
	array(
		'taxonomy'   => 'product_cat',
		'hide_empty' => false,
	)
);
$edit_sid    = isset( $_GET['edit_seg'] ) ? sanitize_text_field( $_GET['edit_seg'] ) : '';
$edit_seg    = ( $edit_sid && isset( $segments[ $edit_sid ] ) ) ? $segments[ $edit_sid ] : null;

require_once __DIR__ . '/../ui-system/wrapper-start.php';
?>
<div class="gt-page-header gt-animate-in">
	<div>
		<h1 class="gt-page-title">👥 Customer Segments</h1>
		<p class="gt-page-subtitle">Target BOGO rules at specific customer groups — by order history, spend, role, or behaviour</p>
	</div>
	<div style="display:flex;gap:8px;align-items:center">
		<span class="gt-badge gt-badge-active"><?php echo esc_html( count( $segments ) ); ?> Segment<?php echo count( $segments ) !== 1 ? 's' : ''; ?></span>
		<span class="gt-badge <?php echo esc_html( $active_segs ) ? 'gt-badge-active' : 'gt-badge-free'; ?>"><?php echo esc_html( $active_segs ); ?> active</span>
	</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>Customer Segments let you run BOGO rules for specific customer groups — VIPs, first-time buyers, lapsed customers, or high-spenders — with precision targeting.</p>
	<div style="display:grid;grid-template-columns:repeat(2,1fr);gap:12px;max-width:480px;margin:24px auto 0">
		<?php foreach ( array( 'Target by user role, order count, and lifetime spend', 'Lapsed customer re-engagement rules', 'First-order incentives for new customers', 'Email domain targeting for B2B deals' ) 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 endif; ?>
<?php $has_seg_pack = function_exists( 'gt_bogo_feature_available' ) && ( gt_bogo_feature_available( 'vip_loyalty' ) || gt_bogo_feature_available( 'new_customer' ) ); ?>
<?php if ( $is_pro && ! $has_seg_pack ) : ?>
<div class="gt-card gt-animate-in" style="margin-bottom:20px;border-color:rgba(225,0,0,0.25);background:rgba(225,0,0,0.04)">
	<div style="display:flex;align-items:center;justify-content:space-between;gap:20px;padding:18px 24px;flex-wrap:wrap">
		<div style="display:flex;align-items:center;gap:14px">
			<span style="font-size:26px">👥</span>
			<div>
				<div style="font-size:14px;font-weight:800;color:var(--gt-white);margin-bottom:3px">Pack Required to Create Segments</div>
				<div style="font-size:13px;color:var(--gt-subtle)">Unlock customer targeting by purchasing the <strong style="color:var(--gt-white)">VIP &amp; Loyalty Rewards</strong> or <strong style="color:var(--gt-white)">New Customer Acquisition</strong> pack</div>
			</div>
		</div>
		<div style="display:flex;gap:10px;flex-shrink:0;flex-wrap:wrap">
			<div id="paypal-container-WEL53HVYRYWPC" style="min-height:40px;min-width:150px"></div>
			<div id="paypal-container-QACS4M9B7H4MW" style="min-height:40px;min-width:150px"></div>
		</div>
	</div>
</div>
<?php endif; ?>
<?php if ( $is_pro ) : ?>

<!-- METRICS -->
<div class="gt-metrics gt-animate-in" style="margin-bottom:20px">
	<div class="gt-metric" style="--gt-metric-c:#e10000">
		<span class="gt-metric-icon">👥</span>
		<div class="gt-metric-label">Total Segments</div>
		<div class="gt-metric-value"><?php echo esc_html( count( $segments ) ); ?></div>
		<div class="gt-metric-trend"><?php echo esc_html( $active_segs ); ?> active</div>
	</div>
	<div class="gt-metric" style="--gt-metric-c:#22c55e">
		<span class="gt-metric-icon">🎯</span>
		<div class="gt-metric-label">Rules Targeted</div>
		<div class="gt-metric-value"><?php echo count( array_unique( array_merge( ...array_map( fn( $s )=> (array) ( $s['rule_ids'] ?? array() ), $segments ) ) ) ); ?></div>
		<div class="gt-metric-trend">Rules with segment targeting</div>
	</div>
	<div class="gt-metric" style="--gt-metric-c:#3b82f6">
		<span class="gt-metric-icon">🔑</span>
		<div class="gt-metric-label">User Roles</div>
		<div class="gt-metric-value"><?php echo esc_html( count( $wp_roles ) ); ?></div>
		<div class="gt-metric-trend">Available for targeting</div>
	</div>
	<div class="gt-metric" style="--gt-metric-c:#8b5cf6">
		<span class="gt-metric-icon">🛍️</span>
		<div class="gt-metric-label">Product Categories</div>
		<div class="gt-metric-value"><?php echo esc_html( count( $categories ) ); ?></div>
		<div class="gt-metric-trend">For purchase-history targeting</div>
	</div>
</div>

<!-- SEGMENT LIST -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
	<div class="gt-card-header">
		<h2 class="gt-card-title">👥 Segments</h2>
		<a href="?page=gt-bogo-engine&tab=segments&new_seg=1" class="gt-btn gt-btn-primary gt-btn-sm">+ New Segment</a>
	</div>
	<?php if ( ! empty( $segments ) ) : ?>
	<div style="display:flex;flex-direction:column;gap:10px">
		<?php
		foreach ( $segments as $sid => $seg ) :
			$c          = $seg['conditions'] ?? array();
			$cond_parts = array();
			if ( ! empty( $c['roles'] ) ) {
				$cond_parts[] = 'Roles: ' . implode( ', ', array_map( fn( $r )=>$wp_roles[ $r ] ?? $r, (array) $c['roles'] ) );
			}
			if ( ! empty( $c['min_orders'] ) ) {
				$cond_parts[] = 'Min ' . $c['min_orders'] . ' orders';
			}
			if ( ! empty( $c['max_orders'] ) ) {
				$cond_parts[] = 'Max ' . $c['max_orders'] . ' orders';
			}
			if ( ! empty( $c['min_spend'] ) ) {
				$cond_parts[] = 'Min spend $' . number_format( $c['min_spend'], 2 );
			}
			if ( ! empty( $c['days_since_last'] ) ) {
				$cond_parts[] = 'Inactive ' . $c['days_since_last'] . '+d';
			}
			if ( ! empty( $c['email_domain'] ) ) {
				$cond_parts[] = 'Domain: ' . $c['email_domain'];
			}
			$assigned = count( (array) ( $seg['rule_ids'] ?? array() ) );
			?>
		<div style="padding:16px 20px;border-radius:10px;border:1px solid <?php echo ! empty( $seg['enabled'] ) ? 'rgba(225,0,0,0.2)' : 'var(--gt-border)'; ?>;background:rgba(255,255,255,0.01)">
			<div style="display:flex;align-items:flex-start;justify-content:space-between;flex-wrap:wrap;gap:12px">
				<div style="flex:1">
					<div style="display:flex;align-items:center;gap:10px;margin-bottom:6px">
						<span style="font-size:14px;font-weight:800;color:var(--gt-white)"><?php echo esc_html( $seg['name'] ); ?></span>
						<span style="font-size:13px;font-weight:700;color:<?php echo $seg['mode'] === 'include' ? '#86efac' : '#fca5a5'; ?>;background:rgba(255,255,255,0.04);padding:2px 10px;border-radius:50px"><?php echo esc_html( strtoupper( $seg['mode'] ) ); ?></span>
						<span class="gt-badge <?php echo ! empty( $seg['enabled'] ) ? 'gt-badge-active' : 'gt-badge-free'; ?>" style="font-size:13px"><?php echo ! empty( $seg['enabled'] ) ? 'Active' : 'Inactive'; ?></span>
					</div>
					<div style="font-size:13px;color:var(--gt-soft)"><?php echo esc_html( implode( ' · ', $cond_parts ) ?: 'No conditions — matches all customers' ); ?></div>
					<?php
					if ( $seg['description'] ) :
						?>
						<div style="font-size:13px;color:var(--gt-subtle);margin-top:3px;font-style:italic"><?php echo esc_html( $seg['description'] ); ?></div><?php endif; ?>
					<div style="font-size:13px;color:var(--gt-subtle);margin-top:3px"><?php echo esc_html( $assigned ); ?> rule<?php echo $assigned !== 1 ? 's' : ''; ?> assigned · Updated <?php echo esc_html( substr( $seg['updated'] ?? '', 0, 10 ) ); ?></div>
				</div>
				<div style="display:flex;gap:8px;flex-wrap:wrap">
					<a href="?page=gt-bogo-engine&tab=segments&edit_seg=<?php echo esc_attr( $sid ); ?>" class="gt-btn gt-btn-ghost gt-btn-sm">✎ Edit</a>
					<a href="
					<?php
					echo esc_url(
						wp_nonce_url(
							add_query_arg(
								array(
									'toggle_seg' => $sid,
									'page'       => 'gt-bogo-engine',
									'tab'        => 'segments',
								),
								admin_url( 'admin.php' )
							),
							'toggle_seg_' . $sid
						)
					);
					?>
								" class="gt-btn gt-btn-ghost gt-btn-sm"><?php echo ! empty( $seg['enabled'] ) ? '⏸ Disable' : '▶ Enable'; ?></a>
					<a href="
					<?php
					echo esc_url(
						wp_nonce_url(
							add_query_arg(
								array(
									'del_seg' => $sid,
									'page'    => 'gt-bogo-engine',
									'tab'     => 'segments',
								),
								admin_url( 'admin.php' )
							),
							'del_seg_' . $sid
						)
					);
					?>
								" class="gt-btn gt-btn-ghost gt-btn-sm" style="color:#fca5a5" onclick="return confirm('Delete this segment?')">✕</a>
				</div>
			</div>
		</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 Segments Yet</h3>
		<p class="gt-text-soft" style="font-size:13px">Create segments to target rules at specific customer groups.</p>
		<a href="?page=gt-bogo-engine&tab=segments&new_seg=1" class="gt-btn gt-btn-primary gt-btn-sm" style="margin-top:16px">+ Create First Segment</a>
	</div>
	<?php endif; ?>
</div>

<!-- SEGMENT FORM -->
	<?php if ( isset( $_GET['new_seg'] ) || $edit_seg ) : ?>
<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_seg ) ? '✎ Edit: ' . esc_html( $edit_seg['name'] ) : '➕ New Segment'; ?></h2>
		<a href="?page=gt-bogo-engine&tab=segments" class="gt-btn gt-btn-ghost gt-btn-sm">✕ Cancel</a>
	</div>
	<form method="post" action="">
		<?php wp_nonce_field( 'gtbogo_save_segment' ); ?>
		<?php
		if ( $edit_seg ) :
			?>
			<input type="hidden" name="segment_id" value="<?php echo esc_attr( $edit_sid ); ?>"><?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">Segment Name</label>
				<input type="text" name="seg_name" class="gt-input" value="<?php echo esc_attr( $edit_seg['name'] ?? '' ); ?>" placeholder="e.g. VIP Customers" required id="gtbogo_seg_name" aria-label="Seg Name">
			</div>
			<div class="gt-form-group">
				<label class="gt-form-label">Mode</label>
				<select name="seg_mode" class="gt-select">
					<option value="include" <?php selected( $edit_seg['mode'] ?? 'include', 'include' ); ?>>Include — rules fire only for this segment</option>
					<option value="exclude" <?php selected( $edit_seg['mode'] ?? '', 'exclude' ); ?>>Exclude — rules are blocked for this segment</option>
				</select>
			</div>
		</div>
		<div class="gt-form-group">
			<label class="gt-form-label">Description (internal)</label>
			<input type="text" name="seg_desc" class="gt-input" value="<?php echo esc_attr( $edit_seg['description'] ?? '' ); ?>" placeholder="e.g. Customers with 3+ orders and $500+ lifetime spend" id="gtbogo_seg_desc" aria-label="Seg Desc">
		</div>

		<!-- CONDITIONS -->
		<div style="font-size:13px;font-weight:700;color:var(--gt-white);text-transform:uppercase;letter-spacing:1px;margin:20px 0 12px">Segment Conditions <span style="font-weight:400;color:var(--gt-subtle);text-transform:none;letter-spacing:0">(ALL conditions must be met)</span></div>

		<div style="display:grid;grid-template-columns:1fr 1fr;gap:20px;margin-bottom:20px">
			<!-- User Roles -->
			<div class="gt-form-group">
				<label class="gt-form-label">User Roles</label>
				<div style="border:1px solid var(--gt-border);border-radius:8px;padding:10px;max-height:160px;overflow-y:auto;display:flex;flex-direction:column;gap:5px">
					<?php
					foreach ( $wp_roles as $slug => $name ) :
						$sel = in_array( $slug, (array) ( $edit_seg['conditions']['roles'] ?? array() ) );
						?>
					<label style="display:flex;align-items:center;gap:8px;cursor:pointer;font-size:13px;color:var(--gt-soft)">
						<input type="checkbox" name="seg_roles[]" value="<?php echo esc_attr( $slug ); ?>" <?php checked( $sel ); ?> style="accent-color:var(--gt-red)">
						<?php echo esc_html( $name ); ?>
					</label>
					<?php endforeach; ?>
				</div>
				<div class="gt-form-hint">Leave blank to match all roles</div>
			</div>

			<!-- Order Count -->
			<div>
				<div class="gt-form-group">
					<label class="gt-form-label">Order Count Range</label>
					<div style="display:flex;gap:10px;align-items:center">
						<input type="number" name="seg_min_orders" class="gt-input" style="flex:1" value="<?php echo esc_attr( $edit_seg['conditions']['min_orders'] ?? 0 ); ?>" min="0" placeholder="Min" id="gtbogo_seg_min_orders" aria-label="Seg Min Orders">
						<span style="color:var(--gt-subtle)">–</span>
						<input type="number" name="seg_max_orders" class="gt-input" style="flex:1" value="<?php echo esc_attr( $edit_seg['conditions']['max_orders'] ?? 0 ); ?>" min="0" placeholder="Max (0=any)" id="gtbogo_seg_max_orders" aria-label="Seg Max Orders">
					</div>
					<div class="gt-form-hint">Total completed orders. 0 = no limit.</div>
				</div>
				<div class="gt-form-group">
					<label class="gt-form-label">Lifetime Spend Range ($)</label>
					<div style="display:flex;gap:10px;align-items:center">
						<input type="number" name="seg_min_spend" class="gt-input" style="flex:1" value="<?php echo esc_attr( $edit_seg['conditions']['min_spend'] ?? 0 ); ?>" min="0" step="0.01" placeholder="Min" id="gtbogo_seg_min_spend" aria-label="Seg Min Spend">
						<span style="color:var(--gt-subtle)">–</span>
						<input type="number" name="seg_max_spend" class="gt-input" style="flex:1" value="<?php echo esc_attr( $edit_seg['conditions']['max_spend'] ?? 0 ); ?>" min="0" step="0.01" placeholder="Max (0=any)" id="gtbogo_seg_max_spend" aria-label="Seg Max Spend">
					</div>
					<div class="gt-form-hint">Total spend across all orders. 0 = no limit.</div>
				</div>
			</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">Days Since Last Order</label>
				<input type="number" name="seg_days_since_last" class="gt-input" value="<?php echo esc_attr( $edit_seg['conditions']['days_since_last'] ?? 0 ); ?>" min="0" id="gtbogo_seg_days_since_last" aria-label="Seg Days Since Last">
				<div class="gt-form-hint">Target lapsed customers. 0 = ignore.</div>
			</div>
			<div class="gt-form-group">
				<label class="gt-form-label">Customer Since (days ago)</label>
				<input type="number" name="seg_days_since_first" class="gt-input" value="<?php echo esc_attr( $edit_seg['conditions']['days_since_first'] ?? 0 ); ?>" min="0" id="gtbogo_seg_days_since_first" aria-label="Seg Days Since First">
				<div class="gt-form-hint">Min days since registration. 0 = ignore.</div>
			</div>
			<div class="gt-form-group">
				<label class="gt-form-label">Registered After</label>
				<input type="date" name="seg_reg_after" class="gt-input" value="<?php echo esc_attr( $edit_seg['conditions']['registered_after'] ?? '' ); ?>" id="gtbogo_seg_reg_after" aria-label="Seg Reg After">
				<div class="gt-form-hint">New customers registered after this date</div>
			</div>
		</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">Has Purchased From Category</label>
				<div style="border:1px solid var(--gt-border);border-radius:8px;padding:10px;max-height:140px;overflow-y:auto;display:flex;flex-direction:column;gap:5px">
					<?php
					foreach ( $categories as $cat ) :
						$sel = in_array( $cat->term_id, array_map( 'intval', (array) ( $edit_seg['conditions']['has_category'] ?? array() ) ) );
						?>
					<label style="display:flex;align-items:center;gap:8px;cursor:pointer;font-size:13px;color:var(--gt-soft)">
						<input type="checkbox" name="seg_has_cat[]" value="<?php echo esc_html( $cat->term_id ); ?>" <?php checked( $sel ); ?> style="accent-color:var(--gt-red)">
						<?php echo esc_html( $cat->name ); ?>
					</label>
					<?php endforeach; ?>
				</div>
				<div class="gt-form-hint">Customer must have previously ordered from one of these categories</div>
			</div>
			<div>
				<div class="gt-form-group">
					<label class="gt-form-label">Email Domain</label>
					<input type="text" name="seg_email_domain" class="gt-input" value="<?php echo esc_attr( $edit_seg['conditions']['email_domain'] ?? '' ); ?>" placeholder="e.g. company.com" id="gtbogo_seg_email_domain" aria-label="Seg Email Domain">
					<div class="gt-form-hint">B2B targeting — match customers with a specific email domain</div>
				</div>
				<div class="gt-form-group">
					<label class="gt-form-label">Has Used a Coupon</label>
					<label style="display:flex;align-items:center;gap:8px;cursor:pointer;margin-top:6px">
						<input type="checkbox" name="seg_coupon_used" value="1" <?php checked( ! empty( $edit_seg['conditions']['coupon_used'] ) ); ?> style="accent-color:var(--gt-red)">
						<span style="font-size:13px;color:var(--gt-soft)">Match customers who have previously used a coupon</span>
					</label>
					<div class="gt-form-hint">Useful for identifying discount-seeking customers</div>
				</div>
			</div>
		</div>

		<!-- ASSIGN RULES -->
			<?php if ( ! empty( $rules ) ) : ?>
		<div class="gt-form-group">
			<label class="gt-form-label">Assign Rules to This Segment</label>
			<div style="border:1px solid var(--gt-border);border-radius:8px;padding:10px;max-height:180px;overflow-y:auto;display:flex;flex-direction:column;gap:6px">
				<?php
				foreach ( $rules as $rule ) :
					$sel = in_array( $rule->id, array_map( 'intval', (array) ( $edit_seg['rule_ids'] ?? array() ) ) );
					?>
				<label style="display:flex;align-items:center;gap:10px;cursor:pointer;padding:4px;border-radius:6px" onmouseover="this.style.background='rgba(255,255,255,0.03)'" onmouseout="this.style.background=''">
					<input type="checkbox" name="seg_rule_ids[]" value="<?php echo esc_html( $rule->id ); ?>" <?php checked( $sel ); ?> style="accent-color:var(--gt-red)">
					<span style="font-size:13px;color:var(--gt-white)"><?php echo esc_html( $rule->name ); ?></span>
					<span style="font-size:13px;color:<?php echo $rule->status === 'active' ? '#86efac' : '#94a3b8'; ?>;margin-left:auto"><?php echo esc_html( $rule->status ); ?></span>
				</label>
				<?php endforeach; ?>
			</div>
			<div class="gt-form-hint">Rules only fire for this segment when assigned here. Leave blank to apply segment conditions to all rules globally.</div>
		</div>
		<?php endif; ?>

		<div class="gt-setting-row" style="border:none;padding:0;margin:16px 0">
			<div><div class="gt-setting-label">Segment Active</div><div class="gt-setting-desc">Inactive segments are saved but not evaluated at checkout</div></div>
			<label class="gt-toggle"><input type="checkbox" name="seg_enabled" value="1" <?php checked( ! empty( $edit_seg['enabled'] ?? true ) ); ?>><span class="gt-toggle-track"><span class="gt-toggle-thumb"></span></span></label>
		</div>

		<div style="display:flex;gap:12px;justify-content:flex-end">
			<a href="?page=gt-bogo-engine&tab=segments" class="gt-btn gt-btn-ghost">Cancel</a>
			<button type="submit" name="gtbogo_save_segment" class="gt-btn gt-btn-primary" style="padding:12px 32px">💾 Save Segment</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">🧠 Segmentation Strategy Guide</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">The Four Essential Segments</div><div style="font-size:13px;color:var(--gt-soft);line-height:1.7">Every store should build: (1) New Customer — 0 orders, registered after a recent date. (2) Loyal — 3+ orders, $200+ spend. (3) Lapsed — last order 60+ days ago. (4) High-Value — top 10% by lifetime spend. Map different BOGO rules to each for fully automated customer lifecycle management.</div></div>
		<div><div style="font-size:13px;font-weight:700;color:var(--gt-white);margin-bottom:6px">Lapsed Customer Re-engagement</div><div style="font-size:13px;color:var(--gt-soft);line-height:1.7">Create a segment with "Days Since Last Order: 60" and an aggressive BOGO rule — full 100% BOGO on first item. Lapsed customers who return convert at 3–5x the rate of cold acquisition. This is your highest-ROI segment. Combine with an exit-intent popup superpower for maximum reach.</div></div>
		<div><div style="font-size:13px;font-weight:700;color:var(--gt-white);margin-bottom:6px">Exclude to Protect Margins</div><div style="font-size:13px;color:var(--gt-soft);line-height:1.7">Use Exclude mode on your wholesale or trade customer roles. These customers already receive bulk pricing — applying BOGO on top of trade pricing can make individual orders loss-making. Exclude your wholesale role from all BOGO rules as a global safeguard.</div></div>
		<div><div style="font-size:13px;font-weight:700;color:var(--gt-white);margin-bottom:6px">B2B Email Domain Targeting</div><div style="font-size:13px;color:var(--gt-soft);line-height:1.7">If you sell to corporate accounts, use the email domain condition to create a segment for specific company domains. Run exclusive BOGO rules for those accounts without making the deal publicly visible. Pair with a hidden deal page (no navigation link) accessible only via direct link sent by email.</div></div>
	</div>
</div>

<?php endif; ?>
<script>
(function(){
	// Live customer count per segment
	document.querySelectorAll('.gt-seg-count-btn').forEach(function(btn) {
		btn.addEventListener('click', function() {
			var sid = this.dataset.sid;
			var el  = document.getElementById('gt-seg-count-' + sid);
			if (!el) return;
			el.textContent = 'Counting...';
			var fd = new FormData();
			fd.append('action', 'gtbogo_count_segment');
			fd.append('nonce', gtBogoAdmin.nonce);
			fd.append('segment_id', sid);
			fetch(ajaxurl, {method:'POST', body:fd, credentials:'same-origin'})
				.then(r => r.json())
				.then(d => {
					if (d.success) el.textContent = d.data.count + ' customers';
					else el.textContent = 'Error';
				}).catch(() => { el.textContent = 'Error'; });
		});
	});

	// AJAX auto-save segment toggles
	document.querySelectorAll('.gt-seg-toggle').forEach(function(toggle) {
		toggle.addEventListener('change', function() {
			var sid     = this.dataset.sid;
			var enabled = this.checked ? 1 : 0;
			var fd = new FormData();
			fd.append('action', 'gtbogo_toggle_segment');
			fd.append('nonce', gtBogoAdmin.nonce);
			fd.append('segment_id', sid);
			fd.append('enabled', enabled);
			fetch(ajaxurl, {method:'POST', body:fd, credentials:'same-origin'})
				.then(r => r.json())
				.then(d => {
					var dot = document.getElementById('gt-seg-dot-' + sid);
					if (dot) dot.style.background = enabled ? '#22c55e' : '#6b7280';
				});
		});
	});
})();
</script>

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