<?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 Intelligence Dashboard
 * Powered by gtbogo_customer_profiles table (v3.14.0).
 * Paginated, sortable, filterable. Scales to millions of customers.
 *
 * @package GT_BOGO_Engine
 * @since   3.14.0
 */

if ( ! function_exists( 'gt_bogo_has_pro' ) || ! gt_bogo_has_pro() ) {
	gtbogo_upgrade_card( 'Customer Intelligence', 'Full customer profile tracking — purchase history, lifetime value, loyalty tier, streak score, birthday, anniversary, and referral count. Every signal feeds the Orchestrator to personalise every deal for every customer automatically.' );
	return;
}
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

global $wpdb;
$tbl    = $wpdb->prefix . 'gtbogo_customer_profiles';
$accent = '#E10000';

// ── Params ────────────────────────────────────────────────────────────────────
$per_page     = 50;
$current_page = max( 1, (int) ( $_GET['paged'] ?? 1 ) );
$sort_by      = in_array( $_GET['sort'] ?? 'last_order_date', array( 'last_order_date', 'total_spent', 'total_orders', 'streak_count', 'avg_order_value', 'lifecycle_state' ) ) ? $_GET['sort'] : 'last_order_date';
$sort_dir     = ( ( $_GET['dir'] ?? 'desc' ) === 'asc' ) ? 'ASC' : 'DESC';
$filter_tier  = sanitize_key( $_GET['tier'] ?? '' );
$filter_state = sanitize_key( $_GET['state'] ?? '' );
$search       = sanitize_text_field( $_GET['s'] ?? '' );
$offset       = ( $current_page - 1 ) * $per_page;

// ── WHERE ─────────────────────────────────────────────────────────────────────
$where  = array( '1=1' );
$params = array();
if ( $search ) {
	$where[]  = '(customer_email LIKE %s)';
	$params[] = '%' . $wpdb->esc_like( $search ) . '%';
}
if ( $filter_tier ) {
	$where[]  = 'vip_tier = %s';
	$params[] = $filter_tier;
}
if ( $filter_state ) {
	$where[]  = 'lifecycle_state = %s';
	$params[] = $filter_state;
}
$where_sql = implode( ' AND ', $where );

// ── Counts ────────────────────────────────────────────────────────────────────
$count_sql   = "SELECT COUNT(*) FROM {$tbl} WHERE {$where_sql}";
$total       = $params ? (int) $wpdb->get_var( $wpdb->prepare( $count_sql, ...$params ) ) : (int) $wpdb->get_var( $count_sql ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
$total_pages = max( 1, ceil( $total / $per_page ) );

// ── Fetch page ────────────────────────────────────────────────────────────────
$select_sql = "SELECT * FROM {$tbl} WHERE {$where_sql} ORDER BY {$sort_by} {$sort_dir} LIMIT %d OFFSET %d";
$q_params   = array_merge( $params, array( $per_page, $offset ) );
$rows       = $wpdb->get_results( $wpdb->prepare( $select_sql, ...$q_params ), ARRAY_A ) ?: array(); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared

// ── KPI stats (SQL — fast at any scale) ──────────────────────────────────────
$kpi = $wpdb->get_row(
	"SELECT // 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
    COUNT(*)                                    AS total,
    SUM(total_spent)                            AS total_ltv,
    AVG(total_spent)                            AS avg_ltv,
    AVG(streak_count)                           AS avg_streak,
    SUM(CASE WHEN vip_tier IS NOT NULL THEN 1 ELSE 0 END) AS vip_count,
    SUM(CASE WHEN lifecycle_state='at_risk' THEN 1 ELSE 0 END) AS at_risk,
    SUM(CASE WHEN lifecycle_state='lapsed' THEN 1 ELSE 0 END)  AS lapsed,
    SUM(CASE WHEN lifecycle_state='new' THEN 1 ELSE 0 END)     AS new_customers,
    SUM(CASE WHEN streak_count >= 3 THEN 1 ELSE 0 END)         AS active_streaks
    FROM {$tbl}",
	ARRAY_A
) ?: array();

// ── Lifecycle distribution ────────────────────────────────────────────────────
$lifecycle_dist = $wpdb->get_results( // 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
	"SELECT lifecycle_state, COUNT(*) AS cnt FROM {$tbl} GROUP BY lifecycle_state ORDER BY cnt DESC",
	ARRAY_A
) ?: array();

// ── VIP tier distribution ─────────────────────────────────────────────────────
$vip_dist = $wpdb->get_results( // 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
	"SELECT vip_tier, COUNT(*) AS cnt FROM {$tbl} WHERE vip_tier IS NOT NULL GROUP BY vip_tier ORDER BY cnt DESC",
	ARRAY_A
) ?: array();

// ── Email engagement stats ────────────────────────────────────────────────────
$email_stats = ( class_exists( 'GT_BOGO_Email_Dedup_Engine' ) && method_exists( 'GT_BOGO_Email_Dedup_Engine', 'get_engagement_stats' ) )
	? GT_BOGO_Email_Dedup_Engine::get_engagement_stats()
	: array();

// ── Rule performance ──────────────────────────────────────────────────────────
$top_rules = ( class_exists( 'GT_BOGO_Rule_Application_Logger' ) && method_exists( 'GT_BOGO_Rule_Application_Logger', 'get_top_rules' ) )
	? GT_BOGO_Rule_Application_Logger::get_top_rules( 30, 5 )
	: array();

// ── Sort URL helper ───────────────────────────────────────────────────────────
if ( ! function_exists( 'gtbogo_ci_sort_url' ) ) {
	function gtbogo_ci_sort_url( string $col, string $current_sort, string $current_dir ): string {
		$new_dir = ( $current_sort === $col && $current_dir === 'DESC' ) ? 'asc' : 'desc';
		return add_query_arg(
			array(
				'sort'  => $col,
				'dir'   => $new_dir,
				'paged' => 1,
			)
		);
	}
}
if ( ! function_exists( 'gtbogo_ci_sort_icon' ) ) {
	function gtbogo_ci_sort_icon( string $col, string $current_sort, string $current_dir ): string {
		if ( $col !== $current_sort ) {
			return '<span style="color:#334155"> ↕</span>';
		}
		return $current_dir === 'DESC' ? '<span style="color:#E10000"> ↓</span>' : '<span style="color:#E10000"> ↑</span>';
	}
}

// ── Lifecycle state colors ────────────────────────────────────────────────────
$state_colors = array(
	'new'          => '#22c55e',
	'returning'    => '#3b82f6',
	'loyal'        => '#6366f1',
	'vip_bronze'   => '#cd7f32',
	'vip_silver'   => '#94a3b8',
	'vip_gold'     => '#f59e0b',
	'vip_platinum' => '#e2e8f0',
	'at_risk'      => '#f97316',
	'lapsed'       => '#ef4444',
	'winback'      => '#a855f7',
);

require GT_BOGO_ENGINE_DIR . 'includes/admin/ui-system/wrapper-start.php';
?>

<style>
.ci-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(160px,1fr));gap:16px;margin-bottom:24px}
.ci-card{background:var(--gt-card,#0a1628);border:1px solid var(--gt-border,#0f1a30);border-radius:10px;padding:18px 20px}
.ci-card .val{font-size:26px;font-weight:800;color:#fff;line-height:1}
.ci-card .lbl{font-size:11px;font-weight:700;letter-spacing:.08em;text-transform:uppercase;color:#4a6a8a;margin-top:5px}
.ci-table{width:100%;border-collapse:collapse;font-size:13px}
.ci-table th{background:#050a16;color:#4a6a8a;font-size:11px;font-weight:700;letter-spacing:.08em;text-transform:uppercase;padding:11px 13px;text-align:left;border-bottom:1px solid #0f1a30;white-space:nowrap}
.ci-table th a{color:#4a6a8a;text-decoration:none}
.ci-table th a:hover{color:#fff}
.ci-table td{padding:11px 13px;border-bottom:1px solid #0f1a30;vertical-align:middle;color:#c8d8e8}
.ci-table tr:hover td{background:rgba(255,255,255,.02)}
.ci-table tr:last-child td{border-bottom:none}
.state-pill{display:inline-block;padding:2px 10px;border-radius:999px;font-size:11px;font-weight:700;border:1px solid}
.ci-section{background:var(--gt-card,#0a1628);border:1px solid var(--gt-border,#0f1a30);border-radius:10px;padding:20px 24px;margin-bottom:20px}
</style>

<div style="font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif">

<!-- Header -->
<div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:24px">
	<div>
		<h2 style="margin:0;color:#fff;font-size:22px;font-weight:700">Customer Intelligence</h2>
		<p style="margin:5px 0 0;color:#4a6a8a;font-size:13px">
			<?php echo esc_html( number_format( (int) ( $kpi['total'] ?? 0 ) ) ); ?> customers tracked &middot; Last updated <?php echo esc_html( gmdate( 'F j, Y g:i a' ) ); ?>
		</p>
	</div>
	<a href="<?php echo esc_url( add_query_arg( array( 'gtbogo_ci_export' => 'csv' ) ) ); ?>"
		style="padding:8px 20px;background:#E10000;border-radius:999px;color:#fff;font-size:13px;font-weight:700;text-decoration:none">
		Export CSV
	</a>
</div>

<!-- KPI cards -->
<div class="ci-grid">
	<div class="ci-card" style="border-top:3px solid #E10000">
		<div class="val"><?php echo esc_html( number_format( (int) ( $kpi['total'] ?? 0 ) ) ); ?></div>
		<div class="lbl">Total Customers</div>
	</div>
	<div class="ci-card" style="border-top:3px solid #22c55e">
		<div class="val"><?php echo wp_kses_post( wc_price( (float) ( $kpi['avg_ltv'] ?? 0 ) ) ); ?></div>
		<div class="lbl">Avg LTV</div>
	</div>
	<div class="ci-card" style="border-top:3px solid #6366f1">
		<div class="val"><?php echo number_format( (int) ( $kpi['vip_count'] ?? 0 ) ); ?></div>
		<div class="lbl">VIP Customers</div>
	</div>
	<div class="ci-card" style="border-top:3px solid #f97316">
		<div class="val"><?php echo number_format( (int) ( $kpi['at_risk'] ?? 0 ) ); ?></div>
		<div class="lbl">At Risk</div>
	</div>
	<div class="ci-card" style="border-top:3px solid #ef4444">
		<div class="val"><?php echo number_format( (int) ( $kpi['lapsed'] ?? 0 ) ); ?></div>
		<div class="lbl">Lapsed</div>
	</div>
	<div class="ci-card" style="border-top:3px solid #3b82f6">
		<div class="val"><?php echo number_format( (int) ( $kpi['active_streaks'] ?? 0 ) ); ?></div>
		<div class="lbl">Active Streaks</div>
	</div>
	<div class="ci-card" style="border-top:3px solid #f59e0b">
		<div class="val"><?php echo number_format( round( (float) ( $kpi['avg_streak'] ?? 0 ), 1 ) ); ?></div>
		<div class="lbl">Avg Streak</div>
	</div>
	<div class="ci-card" style="border-top:3px solid #22c55e">
		<div class="val"><?php echo number_format( (int) ( $kpi['new_customers'] ?? 0 ) ); ?></div>
		<div class="lbl">New Customers</div>
	</div>
</div>

<!-- Lifecycle + Email stats row -->
<div style="display:grid;grid-template-columns:1fr 1fr;gap:20px;margin-bottom:20px">

	<!-- Lifecycle distribution -->
	<div class="ci-section">
		<p style="margin:0 0 14px;font-size:12px;font-weight:700;letter-spacing:.06em;text-transform:uppercase;color:#4a6a8a">Lifecycle Distribution</p>
		<?php
		foreach ( $lifecycle_dist as $ld ) :
			$pct = ( $kpi['total'] ?? 0 ) > 0 ? round( ( $ld['cnt'] / $kpi['total'] ) * 100, 1 ) : 0;
			$col = $state_colors[ $ld['lifecycle_state'] ] ?? '#64748b';
			?>
		<div style="display:flex;align-items:center;gap:10px;margin-bottom:8px">
			<span style="width:110px;font-size:12px;color:#c8d8e8;text-transform:capitalize"><?php echo esc_html( str_replace( '_', ' ', $ld['lifecycle_state'] ) ); ?></span>
			<div style="flex:1;background:#0f1a30;border-radius:999px;height:8px;overflow:hidden">
				<div style="width:<?php echo esc_html( $pct ); ?>%;background:<?php echo esc_html( $col ); ?>;height:100%;border-radius:999px"></div>
			</div>
			<span style="width:50px;font-size:12px;color:#64748b;text-align:right"><?php echo esc_html( number_format( $ld['cnt'] ) ); ?></span>
		</div>
		<?php endforeach; ?>
	</div>

	<!-- Email engagement + top rules -->
	<div class="ci-section">
		<p style="margin:0 0 14px;font-size:12px;font-weight:700;letter-spacing:.06em;text-transform:uppercase;color:#4a6a8a">Email Engagement</p>
		<?php if ( ! empty( $email_stats ) ) : ?>
		<div style="display:grid;grid-template-columns:1fr 1fr;gap:12px;margin-bottom:16px">
			<div><div style="font-size:22px;font-weight:800;color:#fff"><?php echo esc_html( number_format( $email_stats['total_sent'] ?? 0 ) ); ?></div><div style="font-size:11px;color:#4a6a8a;margin-top:3px">Total Sent</div></div>
			<div><div style="font-size:22px;font-weight:800;color:#22c55e"><?php echo esc_html( number_format( $email_stats['sent_today'] ?? 0 ) ); ?></div><div style="font-size:11px;color:#4a6a8a;margin-top:3px">Today</div></div>
			<div><div style="font-size:22px;font-weight:800;color:#3b82f6"><?php echo esc_html( number_format( $email_stats['sent_this_month'] ?? 0 ) ); ?></div><div style="font-size:11px;color:#4a6a8a;margin-top:3px">This Month</div></div>
			<div><div style="font-size:22px;font-weight:800;color:#f59e0b"><?php echo esc_html( count( $email_stats['by_template'] ?? array() ) ); ?></div><div style="font-size:11px;color:#4a6a8a;margin-top:3px">Templates Used</div></div>
		</div>
		<?php endif; ?>
		<?php if ( ! empty( $top_rules ) ) : ?>
		<p style="margin:0 0 10px;font-size:12px;font-weight:700;letter-spacing:.06em;text-transform:uppercase;color:#4a6a8a">Top Rules (30d)</p>
			<?php foreach ( array_slice( $top_rules, 0, 3 ) as $rule ) : ?>
		<div style="display:flex;justify-content:space-between;align-items:center;padding:6px 0;border-bottom:1px solid #0f1a30">
			<span style="font-size:12px;color:#c8d8e8"><?php echo esc_html( $rule['name'] ?? 'Rule #' . $rule['id'] ); ?></span>
			<span style="font-size:12px;color:#E10000;font-weight:700"><?php echo esc_html( number_format( $rule['fires'] ) ); ?> fires</span>
		</div>
		<?php endforeach; ?>
		<?php endif; ?>
	</div>
</div>

<!-- Filters -->
<div class="ci-section" style="padding:14px 20px;margin-bottom:20px">
	<form method="GET" style="display:flex;gap:10px;align-items:center;flex-wrap:wrap">
		<?php
		foreach ( $_GET as $k => $v ) :
			if ( in_array( $k, array( 's', 'tier', 'state', 'sort', 'dir' ) ) ) {
				continue;}
			?>
		<input type="hidden" name="<?php echo esc_attr( $k ); ?>" value="<?php echo esc_attr( $v ); ?>">
		<?php endforeach; ?>
		<input type="hidden" name="page" value="gt-bogo-engine">
		<input type="hidden" name="tab" value="customer-intelligence">
		<input type="text" name="s" placeholder="Search email..."
				value="<?php echo esc_attr( $search ); ?>"
				style="padding:7px 12px;background:#050a16;border:1px solid #0f1a30;border-radius:8px;color:#c8d8e8;font-size:13px;width:200px" id="gtbogo_s" aria-label="S">
		<select name="state" style="padding:7px 12px;background:#050a16;border:1px solid #0f1a30;border-radius:8px;color:#c8d8e8;font-size:13px">
			<option value="">All States</option>
			<?php foreach ( array_keys( $state_colors ) as $st ) : ?>
			<option value="<?php echo esc_html( $st ); ?>" <?php selected( $filter_state, $st ); ?>><?php echo esc_html( ucwords( str_replace( '_', ' ', $st ) ) ); ?></option>
			<?php endforeach; ?>
		</select>
		<select name="tier" style="padding:7px 12px;background:#050a16;border:1px solid #0f1a30;border-radius:8px;color:#c8d8e8;font-size:13px">
			<option value="">All VIP Tiers</option>
			<option value="vip_bronze"   <?php selected( $filter_tier, 'vip_bronze' ); ?>>Bronze</option>
			<option value="vip_silver"   <?php selected( $filter_tier, 'vip_silver' ); ?>>Silver</option>
			<option value="vip_gold"     <?php selected( $filter_tier, 'vip_gold' ); ?>>Gold</option>
			<option value="vip_platinum" <?php selected( $filter_tier, 'vip_platinum' ); ?>>Platinum</option>
		</select>
		<button type="submit" style="padding:7px 16px;background:#E10000;border:none;border-radius:8px;color:#fff;font-size:13px;font-weight:700;cursor:pointer">Filter</button>
		<?php if ( $search || $filter_tier || $filter_state ) : ?>
		<a href="
			<?php
			echo esc_url(
				add_query_arg(
					array(
						's'     => '',
						'tier'  => '',
						'state' => '',
						'paged' => 1,
					)
				)
			);
			?>
					"
			style="padding:7px 16px;background:rgba(255,255,255,.05);border:1px solid #0f1a30;border-radius:8px;color:#64748b;font-size:13px;text-decoration:none">Clear</a>
		<?php endif; ?>
		<span style="margin-left:auto;font-size:12px;color:#4a6a8a">
			<?php echo esc_html( number_format( $total ) ); ?> customer<?php echo $total !== 1 ? 's' : ''; ?>
			<?php
			if ( $total !== (int) ( $kpi['total'] ?? 0 ) ) :
				?>
				(filtered)<?php endif; ?>
		</span>
	</form>
</div>

<!-- Customer table -->
<div class="ci-section" style="padding:0">
	<table class="ci-table">
		<thead>
			<tr>
				<th><a href="<?php echo esc_url( gtbogo_ci_sort_url( 'customer_email', $sort_by, $sort_dir ) ); ?>">Email<?php echo wp_kses_post( gtbogo_ci_sort_icon( 'customer_email', $sort_by, $sort_dir ) ); ?></a></th>
				<th>State / VIP</th>
				<th><a href="<?php echo esc_url( gtbogo_ci_sort_url( 'total_spent', $sort_by, $sort_dir ) ); ?>">LTV<?php echo wp_kses_post( gtbogo_ci_sort_icon( 'total_spent', $sort_by, $sort_dir ) ); ?></a></th>
				<th><a href="<?php echo esc_url( gtbogo_ci_sort_url( 'total_orders', $sort_by, $sort_dir ) ); ?>">Orders<?php echo wp_kses_post( gtbogo_ci_sort_icon( 'total_orders', $sort_by, $sort_dir ) ); ?></a></th>
				<th><a href="<?php echo esc_url( gtbogo_ci_sort_url( 'streak_count', $sort_by, $sort_dir ) ); ?>">Streak<?php echo wp_kses_post( gtbogo_ci_sort_icon( 'streak_count', $sort_by, $sort_dir ) ); ?></a></th>
				<th><a href="<?php echo esc_url( gtbogo_ci_sort_url( 'avg_order_value', $sort_by, $sort_dir ) ); ?>">AOV<?php echo wp_kses_post( gtbogo_ci_sort_icon( 'avg_order_value', $sort_by, $sort_dir ) ); ?></a></th>
				<th><a href="<?php echo esc_url( gtbogo_ci_sort_url( 'last_order_date', $sort_by, $sort_dir ) ); ?>">Last Order<?php echo wp_kses_post( gtbogo_ci_sort_icon( 'last_order_date', $sort_by, $sort_dir ) ); ?></a></th>
				<th>Actions</th>
			</tr>
		</thead>
		<tbody>
		<?php if ( empty( $rows ) ) : ?>
			<tr><td colspan="8" style="text-align:center;padding:48px;color:#4a6a8a">
				No customer profiles yet. Profiles are created automatically when customers place orders.
			</td></tr>
			<?php
		else :
			foreach ( $rows as $row ) :
				$state          = $row['lifecycle_state'] ?? 'new';
				$vip            = $row['vip_tier'] ?? '';
				$state_col      = $state_colors[ $state ] ?? '#64748b';
				$vip_col        = $state_colors[ $vip ] ?? '#64748b';
				$days           = (int) ( $row['days_since_order'] ?? 0 );
				$streak_at_risk = (bool) ( $row['streak_at_risk'] ?? false );
				?>
			<tr>
				<td>
					<a href="
					<?php
					echo esc_url(
						add_query_arg(
							array(
								'page'        => 'gt-bogo-engine',
								'tab'         => 'customer-intelligence',
								'customer_id' => $row['customer_id'],
							)
						)
					);
					?>
			"
						style="color:#fff;font-weight:600;text-decoration:none;font-size:13px">
									<?php echo esc_html( $row['customer_email'] ); ?>
					</a>
					<?php if ( $days > 0 ) : ?>
					<div style="font-size:11px;color:#4a6a8a;margin-top:2px"><?php echo esc_html( $days ); ?>d since order</div>
					<?php endif; ?>
				</td>
				<td>
					<span class="state-pill" style="color:<?php echo esc_html( $state_col ); ?>;border-color:<?php echo esc_html( $state_col ); ?>22;background:<?php echo esc_html( $state_col ); ?>11">
						<?php echo esc_html( ucwords( str_replace( '_', ' ', $state ) ) ); ?>
					</span>
					<?php if ( $vip ) : ?>
					<span class="state-pill" style="color:<?php echo esc_html( $vip_col ); ?>;border-color:<?php echo esc_html( $vip_col ); ?>22;background:<?php echo esc_html( $vip_col ); ?>11;margin-left:4px">
						<?php echo esc_html( ucwords( str_replace( 'vip_', '', $vip ) ) ); ?>
					</span>
					<?php endif; ?>
				</td>
				<td><strong style="color:#fff"><?php echo wp_kses_post( wc_price( (float) ( $row['total_spent'] ?? 0 ) ) ); ?></strong></td>
				<td style="text-align:center"><?php echo (int) ( $row['total_orders'] ?? 0 ); ?></td>
				<td style="text-align:center">
					<?php $streak = (int) ( $row['streak_count'] ?? 0 ); ?>
					<span style="color:<?php echo esc_html( $streak_at_risk ) ? '#f97316' : ( $streak >= 5 ? '#22c55e' : '#c8d8e8' ); ?>;font-weight:<?php echo $streak > 0 ? '700' : '400'; ?>">
						<?php echo esc_html( $streak ); ?>
						<?php
						if ( $streak_at_risk ) :
							?>
							<span style="font-size:10px"> ⚠</span><?php endif; ?>
					</span>
				</td>
				<td><?php echo wp_kses_post( wc_price( (float) ( $row['avg_order_value'] ?? 0 ) ) ); ?></td>
				<td style="font-size:12px;color:#64748b;white-space:nowrap">
					<?php echo $row['last_order_date'] ? esc_html( gmdate( 'M j, Y', strtotime( $row['last_order_date'] ) ) ) : '—'; ?>
				</td>
				<td>
					<?php if ( $row['customer_id'] ) : ?>
					<a href="<?php echo esc_url( get_edit_user_link( $row['customer_id'] ) ); ?>"
						style="padding:4px 12px;background:rgba(225,0,0,.1);border:1px solid rgba(225,0,0,.2);border-radius:6px;color:#fca5a5;font-size:11px;font-weight:700;text-decoration:none">
						WP Profile
					</a>
					<?php endif; ?>
				</td>
			</tr>
				<?php
		endforeach;
endif;
		?>
		</tbody>
	</table>

	<!-- Pagination -->
	<?php
	if ( $total_pages > 1 ) :
		$pg_base = add_query_arg(
			array(
				'sort'  => $sort_by,
				'dir'   => strtolower( $sort_dir ),
				's'     => $search,
				'tier'  => $filter_tier,
				'state' => $filter_state,
			)
		);
		?>
	<div style="display:flex;align-items:center;justify-content:space-between;padding:16px 20px;border-top:1px solid #0f1a30">
		<span style="font-size:12px;color:#4a6a8a">Page <?php echo esc_html( $current_page ); ?> of <?php echo esc_html( $total_pages ); ?> &mdash; <?php echo esc_html( number_format( $total ) ); ?> total</span>
		<div style="display:flex;gap:6px">
			<?php if ( $current_page > 1 ) : ?>
			<a href="<?php echo esc_url( add_query_arg( 'paged', 1, $pg_base ) ); ?>" style="padding:5px 10px;background:#050a16;border:1px solid #0f1a30;border-radius:6px;color:#64748b;font-size:12px;text-decoration:none">« First</a>
			<a href="<?php echo esc_url( add_query_arg( 'paged', $current_page - 1, $pg_base ) ); ?>" style="padding:5px 10px;background:#050a16;border:1px solid #0f1a30;border-radius:6px;color:#64748b;font-size:12px;text-decoration:none">‹ Prev</a>
			<?php endif; ?>
			<?php
			for ( $i = max( 1, $current_page - 2 );$i <= min( $total_pages, $current_page + 2 );$i++ ) :
				$active = $i === $current_page;
				?>
			<a href="<?php echo esc_url( add_query_arg( 'paged', $i, $pg_base ) ); ?>"
				style="padding:5px 10px;background:<?php echo esc_html( $active ) ? '#E10000' : '#050a16'; ?>;border:1px solid <?php echo esc_html( $active ) ? '#E10000' : '#0f1a30'; ?>;border-radius:6px;color:<?php echo esc_html( $active ) ? '#fff' : '#64748b'; ?>;font-size:12px;font-weight:<?php echo esc_html( $active ) ? '700' : '400'; ?>;text-decoration:none">
				<?php echo esc_html( $i ); ?>
			</a>
			<?php endfor; ?>
			<?php if ( $current_page < $total_pages ) : ?>
			<a href="<?php echo esc_url( add_query_arg( 'paged', $current_page + 1, $pg_base ) ); ?>" style="padding:5px 10px;background:#050a16;border:1px solid #0f1a30;border-radius:6px;color:#64748b;font-size:12px;text-decoration:none">Next ›</a>
			<a href="<?php echo esc_url( add_query_arg( 'paged', $total_pages, $pg_base ) ); ?>" style="padding:5px 10px;background:#050a16;border:1px solid #0f1a30;border-radius:6px;color:#64748b;font-size:12px;text-decoration:none">Last »</a>
			<?php endif; ?>
		</div>
	</div>
	<?php endif; ?>
</div>

</div>

<?php require GT_BOGO_ENGINE_DIR . 'includes/admin/ui-system/wrapper-end.php'; ?>
