<?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 — Loyalty Acceleration Dashboard
 *
 * Enterprise loyalty intelligence:
 *   - KPI cards: VIP count, loyal count, LTV multiplier, active streaks
 *   - VIP pipeline funnel (None → Bronze → Silver → Gold → Platinum → Elite)
 *   - Near-tier-upgrade radar ("23 customers are 1 order from Gold")
 *   - Order frequency distribution (Chart.js bar)
 *   - LTV by loyalty tier (Chart.js bar)
 *   - Streak health: active / at-risk / broken streaks this month
 *   - Anniversary & birthday radars
 *   - Loyalty email performance table (nudge_1, nudge_2, vip_unlocked)
 *   - Top 15 loyalists by LTV + orders
 *   - Manual tier override (AJAX customer search + tier set)
 *   - Loyalty ROI calculator
 *
 * @package GT_BOGO_Engine
 * @since   5.0.0
 */
if ( ! function_exists( 'gt_bogo_has_pro' ) || ! gt_bogo_has_pro() ) {
    if ( function_exists( 'gtbogo_upgrade_card' ) ) {
        gtbogo_upgrade_card( 'Loyalty Acceleration Engine',
            'Automatically identifies customers close to the next loyalty tier and fires targeted deals to push them over. Streak bonuses, anniversary rewards, and birthday deals all run on autopilot.' );
    }
    return;
}
if ( ! defined( 'ABSPATH' ) ) exit;

global $wpdb;
$nonce    = wp_create_nonce( 'gtbogo_loyalty_accel' );
$profiles = $wpdb->prefix . 'gtbogo_customer_profiles';
$email_log= $wpdb->prefix . 'gtbogo_email_log';
$has_prof = (bool) $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $profiles ) ); // phpcs:ignore
$has_log  = (bool) $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $email_log ) ); // phpcs:ignore

/* ── Core KPIs ──────────────────────────────────────────────────────────── */
$kpi = get_transient( 'gtbogo_la_kpi_v4' );
if ( false === $kpi && $has_prof ) {
    $kpi = [
        'vip_count'       => (int)   $wpdb->get_var( "SELECT COUNT(*) FROM {$profiles} WHERE vip_tier IS NOT NULL AND vip_tier != ''" ), // phpcs:ignore
        'loyal_count'     => (int)   $wpdb->get_var( "SELECT COUNT(*) FROM {$profiles} WHERE lifecycle_state='loyal'" ), // phpcs:ignore
        'total_customers' => (int)   $wpdb->get_var( "SELECT COUNT(*) FROM {$profiles}" ), // phpcs:ignore
        'avg_ltv_vip'     => (float) $wpdb->get_var( "SELECT AVG(total_spent) FROM {$profiles} WHERE vip_tier IS NOT NULL AND vip_tier!='' AND total_spent>0" ), // phpcs:ignore
        'avg_ltv_all'     => (float) $wpdb->get_var( "SELECT AVG(total_spent) FROM {$profiles} WHERE total_spent>0" ), // phpcs:ignore
        'with_streaks'    => (int)   $wpdb->get_var( "SELECT COUNT(*) FROM {$profiles} WHERE purchase_streak > 1" ), // phpcs:ignore
        'max_streak'      => (int)   $wpdb->get_var( "SELECT MAX(purchase_streak) FROM {$profiles}" ), // phpcs:ignore
    ];
    set_transient( 'gtbogo_la_kpi_v4', $kpi, 5 * MINUTE_IN_SECONDS );
}
$kpi = $kpi ?: [];

$ltv_mult = ( (float)($kpi['avg_ltv_all']??0) > 0 )
    ? round( (float)($kpi['avg_ltv_vip']??0) / (float)($kpi['avg_ltv_all']??1), 1 )
    : 0;

/* ── Tier distribution ──────────────────────────────────────────────────── */
$tier_dist = [];
if ( $has_prof ) {
    $tiers = ['bronze','silver','gold','platinum','elite'];
    foreach ( $tiers as $t ) {
        $tier_dist[$t] = (int) $wpdb->get_var( $wpdb->prepare( // phpcs:ignore
            "SELECT COUNT(*) FROM {$profiles} WHERE vip_tier = %s", $t
        ) );
    }
    $tier_dist['none'] = (int) $wpdb->get_var( // phpcs:ignore
        "SELECT COUNT(*) FROM {$profiles} WHERE vip_tier IS NULL OR vip_tier=''"
    );
}

/* ── Near-upgrade radar ─────────────────────────────────────────────────── */
$near_upgrade = [];
$tier_thresholds = [
    'bronze'   => [ 'orders' => 2,  'next' => 'Silver' ],
    'silver'   => [ 'orders' => 5,  'next' => 'Gold' ],
    'gold'     => [ 'orders' => 10, 'next' => 'Platinum' ],
    'platinum' => [ 'orders' => 20, 'next' => 'Elite' ],
];
if ( $has_prof ) {
    foreach ( $tier_thresholds as $tier => $thresh ) {
        // Customers who are 1-2 orders from next tier
        $count = (int) $wpdb->get_var( $wpdb->prepare( // phpcs:ignore
            "SELECT COUNT(*) FROM {$profiles}
             WHERE vip_tier = %s
             AND total_orders BETWEEN %d AND %d",
            $tier, $thresh['orders'] - 2, $thresh['orders'] - 1
        ) );
        if ( $count > 0 ) {
            $near_upgrade[] = [
                'current_tier' => ucfirst($tier),
                'next_tier'    => $thresh['next'],
                'count'        => $count,
                'orders_away'  => 1,
            ];
        }
    }
}

/* ── Order frequency distribution ──────────────────────────────────────── */
$order_dist = [];
if ( $has_prof ) {
    $rows = $wpdb->get_results( // phpcs:ignore
        "SELECT LEAST(total_orders, 6) AS band, COUNT(*) AS cnt
         FROM {$profiles} WHERE total_orders > 0
         GROUP BY band ORDER BY band ASC",
        ARRAY_A
    ) ?: [];
    foreach ($rows as $r) {
        $label = (int)$r['band'] >= 6 ? '6+' : (string)(int)$r['band'];
        $order_dist[$label] = ($order_dist[$label]??0) + (int)$r['cnt'];
    }
}

/* ── LTV by tier for chart ──────────────────────────────────────────────── */
$ltv_by_tier = [];
if ( $has_prof ) {
    $tier_list = ['none','bronze','silver','gold','platinum','elite'];
    foreach ($tier_list as $t) {
        $cond = $t==='none' ? "WHERE (vip_tier IS NULL OR vip_tier='')" : $wpdb->prepare("WHERE vip_tier=%s",$t);
        $ltv_by_tier[$t] = round((float)$wpdb->get_var("SELECT AVG(total_spent) FROM {$profiles} {$cond} AND total_spent>0"),2); // phpcs:ignore
    }
}

/* ── Streak health ──────────────────────────────────────────────────────── */
$streak_data = [];
if ( $has_prof ) {
    $streak_data = [
        'active_2plus'  => (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$profiles} WHERE purchase_streak >= 2" ), // phpcs:ignore
        'active_5plus'  => (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$profiles} WHERE purchase_streak >= 5" ), // phpcs:ignore
        'at_risk'       => (int) $wpdb->get_var( // phpcs:ignore
            "SELECT COUNT(*) FROM {$profiles}
             WHERE purchase_streak >= 2
             AND last_order_date < DATE_SUB(UTC_DATE(), INTERVAL 25 DAY)
             AND last_order_date > DATE_SUB(UTC_DATE(), INTERVAL 35 DAY)"
        ),
        'streak_1'      => (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$profiles} WHERE purchase_streak = 1" ), // phpcs:ignore
    ];
}

/* ── Anniversary radar (next 14 days) ───────────────────────────────────── */
$anniversaries = [];
if ( $has_prof ) {
    $anniv_col = 'first_order_date';
    $cols = $wpdb->get_col("DESCRIBE `{$profiles}`", 0); // phpcs:ignore
    if (in_array($anniv_col, $cols, true)) {
        $anniversaries = (int) $wpdb->get_var( // phpcs:ignore
            "SELECT COUNT(*) FROM {$profiles}
             WHERE DAYOFYEAR(first_order_date) BETWEEN DAYOFYEAR(UTC_DATE()) AND DAYOFYEAR(DATE_ADD(UTC_DATE(), INTERVAL 14 DAY))
             AND first_order_date < DATE_SUB(UTC_DATE(), INTERVAL 365 DAY)"
        );
    }
}

/* ── Email nudge performance ────────────────────────────────────────────── */
$nudge_stats = [];
if ( $has_log ) {
    foreach ( ['loyalty_nudge_1','loyalty_nudge_2','vip_unlocked','streak_bonus','tier_upgrade'] as $tpl ) {
        $sent    = (int) $wpdb->get_var( $wpdb->prepare("SELECT COUNT(*) FROM {$email_log} WHERE template=%s",$tpl) ); // phpcs:ignore
        $opened  = (int) $wpdb->get_var( $wpdb->prepare("SELECT COUNT(*) FROM {$email_log} WHERE template=%s AND opened_at IS NOT NULL",$tpl) ); // phpcs:ignore
        $clicked = (int) $wpdb->get_var( $wpdb->prepare("SELECT COUNT(*) FROM {$email_log} WHERE template=%s AND clicked_at IS NOT NULL",$tpl) ); // phpcs:ignore
        $nudge_stats[$tpl] = compact('sent','opened','clicked');
    }
}

/* ── Top 15 loyalists ───────────────────────────────────────────────────── */
$top_loyalists = [];
if ( $has_prof ) {
    $top_loyalists = $wpdb->get_results( // phpcs:ignore
        "SELECT customer_id, vip_tier, total_orders, total_spent, purchase_streak, lifecycle_state, last_order_date
         FROM {$profiles}
         WHERE total_spent > 0
         ORDER BY total_spent DESC LIMIT 15",
        ARRAY_A
    ) ?: [];
}

/* ── Chart data JSON ────────────────────────────────────────────────────── */
$od_labels = wp_json_encode( array_keys($order_dist) );
$od_data   = wp_json_encode( array_values($order_dist) );

$tier_chart_labels = wp_json_encode(['None','Bronze','Silver','Gold','Platinum','Elite']);
$tier_chart_data   = wp_json_encode( array_values($ltv_by_tier) );
$tier_chart_colors = wp_json_encode(['#475569','#cd7f32','#94a3b8','#f59e0b','#a855f7','#06b6d4']);

$funnel_labels = wp_json_encode(['No Tier','Bronze','Silver','Gold','Platinum','Elite']);
$funnel_data   = wp_json_encode([
    $tier_dist['none']??0, $tier_dist['bronze']??0, $tier_dist['silver']??0,
    $tier_dist['gold']??0, $tier_dist['platinum']??0, $tier_dist['elite']??0
]);

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">👑 Loyalty Acceleration</h1>
        <p class="gt-page-subtitle">
            VIP pipeline health, tier progression, streak intelligence, and loyalty
            program ROI — all automated by the Loyalty Accelerator engine.
        </p>
    </div>
    <div style="display:flex;gap:10px;flex-wrap:wrap">
        <a href="<?php echo esc_url(admin_url('admin.php?page=gt-bogo-engine&tab=segments')); ?>"
           class="gt-btn gt-btn-ghost gt-btn-sm">Customer Segments →</a>
        <a href="<?php echo esc_url(admin_url('admin.php?page=gt-bogo-engine&tab=emails')); ?>"
           class="gt-btn gt-btn-ghost gt-btn-sm">Email Settings →</a>
    </div>
</div>

<?php if ( ! $has_prof ) : ?>
<div class="gt-card gt-animate-in">
    <div style="padding:40px;text-align:center">
        <div style="font-size:40px;margin-bottom:12px">👑</div>
        <div style="font-size:13px;color:var(--gt-subtle);max-width:480px;margin:0 auto;line-height:1.6">
            The <code>gtbogo_customer_profiles</code> table is not yet populated.
            Customer profiles build automatically as shoppers browse and purchase.
            Data appears here within 24–48 hours of go-live.
        </div>
    </div>
</div>
<?php else : ?>

<!-- ═══════════════════════════════════════════════════════════════════════════
     KPI CARDS
════════════════════════════════════════════════════════════════════════════ -->
<div class="gt-animate-in" style="display:grid;grid-template-columns:repeat(6,1fr);gap:14px;margin-bottom:20px">
    <?php
    $kpis = [
        [ 'VIP Customers',    number_format($kpi['vip_count']??0),    '#f59e0b', 'any tier assigned' ],
        [ 'Loyal Customers',  number_format($kpi['loyal_count']??0),  '#22c55e', 'lifecycle = loyal' ],
        [ 'Total Profiled',   number_format($kpi['total_customers']??0),'#3b82f6','in intelligence system' ],
        [ 'VIP LTV Mult.',    $ltv_mult.'×',                           '#f59e0b', 'vs all-customer avg' ],
        [ 'Active Streaks',   number_format($streak_data['active_2plus']??0),'#22c55e','2+ consecutive orders' ],
        [ 'Streak Risk',      number_format($streak_data['at_risk']??0),'#ef4444','at-risk of breaking' ],
    ];
    foreach ($kpis as $k) : ?>
    <div class="gt-card" style="padding:16px 18px;text-align:center">
        <div style="font-size:24px;font-weight:900;color:<?php echo esc_attr($k[2]); ?>;margin-bottom:4px;line-height:1">
            <?php echo esc_html($k[1]); ?>
        </div>
        <div style="font-size:10px;font-weight:800;letter-spacing:.1em;text-transform:uppercase;color:var(--gt-subtle)">
            <?php echo esc_html($k[0]); ?>
        </div>
        <div style="font-size:10px;color:rgba(100,116,139,0.6);margin-top:2px"><?php echo esc_html($k[3]); ?></div>
    </div>
    <?php endforeach; ?>
</div>

<!-- ═══════════════════════════════════════════════════════════════════════════
     VIP PIPELINE FUNNEL + NEAR-UPGRADE RADAR
════════════════════════════════════════════════════════════════════════════ -->
<div class="gt-animate-in" style="display:grid;grid-template-columns:2fr 1fr;gap:16px;margin-bottom:20px">

    <!-- VIP Tier Funnel -->
    <div class="gt-card">
        <div class="gt-card-header">
            <h2 class="gt-card-title">👑 VIP Tier Pipeline</h2>
            <span style="font-size:12px;color:var(--gt-subtle)">Customer distribution by tier</span>
        </div>
        <?php
        $tier_config = [
            'none'     => [ 'label'=>'No Tier',  'color'=>'#475569', 'icon'=>'○' ],
            'bronze'   => [ 'label'=>'Bronze',    'color'=>'#cd7f32', 'icon'=>'🥉' ],
            'silver'   => [ 'label'=>'Silver',    'color'=>'#94a3b8', 'icon'=>'🥈' ],
            'gold'     => [ 'label'=>'Gold',      'color'=>'#f59e0b', 'icon'=>'🥇' ],
            'platinum' => [ 'label'=>'Platinum',  'color'=>'#a855f7', 'icon'=>'💎' ],
            'elite'    => [ 'label'=>'Elite',     'color'=>'#06b6d4', 'icon'=>'👑' ],
        ];
        $tier_total = max(1, array_sum($tier_dist));
        foreach ($tier_config as $tk => $tv) :
            $tc = (int)($tier_dist[$tk]??0);
            $tp = round($tc / $tier_total * 100);
        ?>
        <div style="display:flex;align-items:center;gap:12px;padding:10px 0;border-bottom:1px solid rgba(255,255,255,0.04)">
            <span style="font-size:18px;width:28px;text-align:center;flex-shrink:0"><?php echo esc_html($tv['icon']); ?></span>
            <div style="width:70px;font-size:12px;font-weight:700;color:<?php echo esc_attr($tv['color']); ?>;flex-shrink:0">
                <?php echo esc_html($tv['label']); ?>
            </div>
            <div style="flex:1;height:8px;background:rgba(255,255,255,0.05);border-radius:4px;overflow:hidden">
                <div style="height:100%;width:<?php echo esc_attr((string)$tp); ?>%;background:<?php echo esc_attr($tv['color']); ?>;border-radius:4px;transition:width 1s ease"></div>
            </div>
            <div style="width:40px;text-align:right;font-size:12px;font-weight:700;color:var(--gt-white)">
                <?php echo esc_html(number_format($tc)); ?>
            </div>
            <div style="width:32px;text-align:right;font-size:10px;color:var(--gt-subtle)"><?php echo esc_html($tp.'%'); ?></div>
        </div>
        <?php endforeach; ?>
    </div>

    <!-- Near-upgrade radar -->
    <div class="gt-card">
        <div class="gt-card-header">
            <h2 class="gt-card-title">🎯 Near Upgrade</h2>
        </div>
        <?php if ( empty($near_upgrade) ) : ?>
        <div style="padding:20px 0;font-size:12px;color:var(--gt-subtle);line-height:1.5">
            No customers are within 1–2 orders of the next tier right now.
            Near-upgrade data builds as customer order counts grow.
        </div>
        <?php else : foreach ($near_upgrade as $nu) : ?>
        <div style="padding:12px 0;border-bottom:1px solid rgba(255,255,255,0.04)">
            <div style="font-size:22px;font-weight:900;color:#22c55e;line-height:1;margin-bottom:3px">
                <?php echo esc_html(number_format($nu['count'])); ?>
            </div>
            <div style="font-size:12px;color:var(--gt-white);font-weight:600">
                <?php echo esc_html($nu['current_tier']); ?> → <?php echo esc_html($nu['next_tier']); ?>
            </div>
            <div style="font-size:11px;color:var(--gt-subtle);margin-top:2px">
                Within 1–2 orders of <?php echo esc_html($nu['next_tier']); ?>
            </div>
            <a href="<?php echo esc_url(admin_url('admin.php?page=gt-bogo-engine&tab=segments')); ?>"
               class="gt-btn gt-btn-primary gt-btn-sm" style="margin-top:8px;display:inline-block">
                Target →
            </a>
        </div>
        <?php endforeach; endif; ?>

        <!-- Anniversaries coming up -->
        <?php if ($anniversaries > 0) : ?>
        <div style="margin-top:12px;padding:10px 12px;background:rgba(245,158,11,0.05);border:1px solid rgba(245,158,11,0.15);border-radius:7px">
            <div style="font-size:12px;font-weight:700;color:#f59e0b;margin-bottom:3px">
                🎂 <?php echo esc_html((string)$anniversaries); ?> anniversaries in next 14 days
            </div>
            <a href="<?php echo esc_url(admin_url('admin.php?page=gt-bogo-engine&tab=emails')); ?>"
               style="font-size:11px;color:var(--gt-red);font-weight:700;text-decoration:none">
                Configure anniversary email →
            </a>
        </div>
        <?php endif; ?>
    </div>
</div>

<!-- ═══════════════════════════════════════════════════════════════════════════
     CHARTS — Order Frequency + LTV by Tier
════════════════════════════════════════════════════════════════════════════ -->
<div class="gt-animate-in" style="display:grid;grid-template-columns:1fr 1fr;gap:16px;margin-bottom:20px">

    <div class="gt-card">
        <div class="gt-card-header">
            <h2 class="gt-card-title">Purchase Frequency Distribution</h2>
            <span style="font-size:12px;color:var(--gt-subtle)">Customers by order count</span>
        </div>
        <div class="gt-chart-wrap" style="height:200px;padding:6px 4px">
            <?php if (empty($order_dist)) : ?>
            <div style="height:200px;display:flex;align-items:center;justify-content:center;color:var(--gt-subtle);font-size:13px">No order data yet</div>
            <?php else : ?>
            <canvas id="gt-la-order-chart"></canvas>
            <?php endif; ?>
        </div>
    </div>

    <div class="gt-card">
        <div class="gt-card-header">
            <h2 class="gt-card-title">Average LTV by Tier</h2>
            <span style="font-size:12px;color:var(--gt-subtle)">Higher tiers = more valuable</span>
        </div>
        <div class="gt-chart-wrap" style="height:200px;padding:6px 4px">
            <?php if (empty(array_filter($ltv_by_tier))) : ?>
            <div style="height:200px;display:flex;align-items:center;justify-content:center;color:var(--gt-subtle);font-size:13px">No LTV data yet</div>
            <?php else : ?>
            <canvas id="gt-la-ltv-chart"></canvas>
            <?php endif; ?>
        </div>
    </div>
</div>

<!-- ═══════════════════════════════════════════════════════════════════════════
     STREAK HEALTH
════════════════════════════════════════════════════════════════════════════ -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
    <div class="gt-card-header">
        <h2 class="gt-card-title">🔥 Streak Health</h2>
        <span style="font-size:12px;color:var(--gt-subtle)">Consecutive purchase streaks across your customer base</span>
    </div>
    <div style="display:grid;grid-template-columns:repeat(4,1fr);gap:0">
        <?php
        $streak_cells = [
            [ 'Active 2+',    $streak_data['active_2plus']??0, '#22c55e', '2+ consecutive orders' ],
            [ 'Active 5+',    $streak_data['active_5plus']??0, '#f59e0b', 'Power streak — 5+ orders' ],
            [ 'At Risk',      $streak_data['at_risk']??0,      '#ef4444', 'No order in 25–35 days' ],
            [ 'Longest',      $streak_data['max_streak']??0,   '#3b82f6', 'Store record streak' ],
        ];
        foreach ($streak_cells as $i => $sc) :
        ?>
        <div style="padding:20px 18px;text-align:center;<?php echo $i<3?'border-right:1px solid var(--gt-border);':''; ?>">
            <div style="font-size:32px;font-weight:900;color:<?php echo esc_attr($sc[2]); ?>;margin-bottom:4px;line-height:1">
                <?php echo esc_html(number_format((int)$sc[1])); ?>
            </div>
            <div style="font-size:10px;font-weight:800;text-transform:uppercase;letter-spacing:.1em;color:var(--gt-subtle)">
                <?php echo esc_html($sc[0]); ?>
            </div>
            <div style="font-size:10px;color:rgba(100,116,139,0.6);margin-top:2px"><?php echo esc_html($sc[3]); ?></div>
        </div>
        <?php endforeach; ?>
    </div>
    <?php if (($streak_data['at_risk']??0) > 0) : ?>
    <div style="padding:10px 20px;background:rgba(239,68,68,0.05);border-top:1px solid rgba(239,68,68,0.1);
                display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:10px">
        <div style="font-size:12px;color:#fca5a5;font-weight:600">
            ⚠ <?php echo esc_html((string)($streak_data['at_risk']??0)); ?> customers are about to break their streak — trigger a win-back email now.
        </div>
        <a href="<?php echo esc_url(admin_url('admin.php?page=gt-bogo-engine&tab=emails')); ?>"
           class="gt-btn gt-btn-sm" style="background:#ef4444;flex-shrink:0">
            Send Streak Nudge →
        </a>
    </div>
    <?php endif; ?>
</div>

<!-- ═══════════════════════════════════════════════════════════════════════════
     EMAIL NUDGE PERFORMANCE
════════════════════════════════════════════════════════════════════════════ -->
<?php if ($has_log && !empty($nudge_stats)) : ?>
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
    <div class="gt-card-header">
        <h2 class="gt-card-title">✉️ Loyalty Email Performance</h2>
        <a href="<?php echo esc_url(admin_url('admin.php?page=gt-bogo-engine&tab=emails')); ?>"
           class="gt-btn gt-btn-ghost gt-btn-sm">Configure Emails →</a>
    </div>
    <div style="overflow-x:auto">
        <table style="width:100%;border-collapse:collapse;font-size:12px">
            <thead>
                <tr style="border-bottom:1px solid var(--gt-border)">
                    <?php foreach (['Email Type','Sent','Opened','Open Rate','Clicked','Click Rate'] as $col) : ?>
                    <th style="padding:9px 14px;text-align:left;font-size:10px;font-weight:800;
                               letter-spacing:.1em;text-transform:uppercase;color:var(--gt-subtle)">
                        <?php echo esc_html($col); ?>
                    </th>
                    <?php endforeach; ?>
                </tr>
            </thead>
            <tbody>
            <?php
            $email_labels = [
                'loyalty_nudge_1' => 'Loyalty Nudge 1',
                'loyalty_nudge_2' => 'Loyalty Nudge 2',
                'vip_unlocked'    => 'VIP Unlocked',
                'streak_bonus'    => 'Streak Bonus',
                'tier_upgrade'    => 'Tier Upgrade',
            ];
            foreach ($nudge_stats as $tpl => $ns) :
                $open_rate  = $ns['sent']>0 ? round($ns['opened']/$ns['sent']*100,1) : 0;
                $click_rate = $ns['sent']>0 ? round($ns['clicked']/$ns['sent']*100,1) : 0;
                $or_c = $open_rate>=25?'#22c55e':($open_rate>=15?'#f59e0b':'#ef4444');
                $cr_c = $click_rate>=3?'#22c55e':($click_rate>=1?'#f59e0b':'#ef4444');
            ?>
            <tr style="border-bottom:1px solid rgba(255,255,255,0.03)">
                <td style="padding:9px 14px;font-weight:600;color:var(--gt-white)">
                    <?php echo esc_html($email_labels[$tpl]??$tpl); ?>
                </td>
                <td style="padding:9px 14px;color:var(--gt-subtle)"><?php echo esc_html(number_format($ns['sent'])); ?></td>
                <td style="padding:9px 14px;color:var(--gt-white)"><?php echo esc_html(number_format($ns['opened'])); ?></td>
                <td style="padding:9px 14px;color:<?php echo esc_attr($or_c); ?>;font-weight:700"><?php echo esc_html($open_rate.'%'); ?></td>
                <td style="padding:9px 14px;color:var(--gt-white)"><?php echo esc_html(number_format($ns['clicked'])); ?></td>
                <td style="padding:9px 14px;color:<?php echo esc_attr($cr_c); ?>;font-weight:700"><?php echo esc_html($click_rate.'%'); ?></td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>
<?php endif; ?>

<!-- ═══════════════════════════════════════════════════════════════════════════
     TOP LOYALISTS TABLE
════════════════════════════════════════════════════════════════════════════ -->
<?php if (!empty($top_loyalists)) : ?>
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
    <div class="gt-card-header">
        <h2 class="gt-card-title">🏆 Top 15 Loyalists</h2>
        <span style="font-size:12px;color:var(--gt-subtle)">Highest LTV customers</span>
    </div>
    <div style="overflow-x:auto">
        <table style="width:100%;border-collapse:collapse;font-size:12px">
            <thead>
                <tr style="border-bottom:1px solid var(--gt-border)">
                    <?php foreach (['#','Customer ID','Tier','Orders','Total LTV','Streak','Lifecycle','Last Order','Action'] as $col) : ?>
                    <th style="padding:9px 12px;text-align:left;font-size:10px;font-weight:800;
                               letter-spacing:.08em;text-transform:uppercase;color:var(--gt-subtle)">
                        <?php echo esc_html($col); ?>
                    </th>
                    <?php endforeach; ?>
                </tr>
            </thead>
            <tbody>
            <?php foreach ($top_loyalists as $idx => $cust) :
                $tier = $cust['vip_tier'] ?: 'none';
                $tier_colors = ['none'=>'#475569','bronze'=>'#cd7f32','silver'=>'#94a3b8','gold'=>'#f59e0b','platinum'=>'#a855f7','elite'=>'#06b6d4'];
                $tc = $tier_colors[$tier] ?? '#64748b';
                $last_order = $cust['last_order_date'] ? human_time_diff(strtotime($cust['last_order_date']), time()).' ago' : '—';
            ?>
            <tr style="border-bottom:1px solid rgba(255,255,255,0.03)">
                <td style="padding:8px 12px;color:var(--gt-subtle);font-size:11px"><?php echo esc_html((string)($idx+1)); ?></td>
                <td style="padding:8px 12px;font-family:'DM Mono','Courier New',monospace;font-size:11px;color:var(--gt-subtle)">
                    #<?php echo esc_html((string)(int)$cust['customer_id']); ?>
                </td>
                <td style="padding:8px 12px">
                    <span style="padding:2px 8px;border-radius:20px;font-size:9px;font-weight:800;text-transform:uppercase;
                                 background:<?php echo esc_attr($tc); ?>18;border:1px solid <?php echo esc_attr($tc); ?>40;
                                 color:<?php echo esc_attr($tc); ?>">
                        <?php echo esc_html(ucfirst($tier)); ?>
                    </span>
                </td>
                <td style="padding:8px 12px;color:var(--gt-white);font-weight:700"><?php echo esc_html(number_format((int)$cust['total_orders'])); ?></td>
                <td style="padding:8px 12px;color:#f59e0b;font-weight:700">$<?php echo esc_html(number_format((float)$cust['total_spent'],0)); ?></td>
                <td style="padding:8px 12px;color:<?php echo (int)$cust['purchase_streak']>=3?'#22c55e':'var(--gt-subtle)'; ?>;font-weight:700">
                    <?php echo esc_html((string)(int)$cust['purchase_streak']); ?>
                </td>
                <td style="padding:8px 12px;color:var(--gt-subtle);font-size:11px"><?php echo esc_html($cust['lifecycle_state']??''); ?></td>
                <td style="padding:8px 12px;color:var(--gt-subtle);font-size:11px"><?php echo esc_html($last_order); ?></td>
                <td style="padding:8px 12px">
                    <?php if ($cust['customer_id']) : ?>
                    <a href="<?php echo esc_url(admin_url('user-edit.php?user_id='.(int)$cust['customer_id'])); ?>"
                       style="font-size:11px;color:var(--gt-red);font-weight:700;text-decoration:none" target="_blank">
                        View →
                    </a>
                    <?php endif; ?>
                </td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>
<?php endif; ?>

<!-- ═══════════════════════════════════════════════════════════════════════════
     MANUAL TIER OVERRIDE
════════════════════════════════════════════════════════════════════════════ -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
    <div class="gt-card-header">
        <h2 class="gt-card-title">🔧 Manual Tier Override</h2>
        <span style="font-size:12px;color:var(--gt-subtle)">Set a customer's loyalty tier manually</span>
    </div>
    <div style="display:flex;gap:10px;flex-wrap:wrap;align-items:flex-end">
        <div class="gt-form-group" style="margin:0;flex:1;min-width:180px">
            <label class="gt-form-label">Customer ID or Email</label>
            <input type="text" id="gt-la-cust-search" class="gt-input" placeholder="42 or name@email.com"
                   oninput="gtLaSearchCustomer()">
        </div>
        <div class="gt-form-group" style="margin:0">
            <label class="gt-form-label">Set Tier</label>
            <select id="gt-la-tier-select" class="gt-select">
                <option value="">Select tier…</option>
                <?php foreach (['none','bronze','silver','gold','platinum','elite'] as $t) : ?>
                <option value="<?php echo esc_attr($t); ?>"><?php echo esc_html(ucfirst($t)); ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <button type="button" class="gt-btn gt-btn-primary"
            onclick="gtLaSetTier('<?php echo esc_js($nonce); ?>')">
            Apply Override
        </button>
    </div>
    <div id="gt-la-override-result" style="display:none;margin-top:12px;font-size:12px;padding:10px 12px;border-radius:7px"></div>
</div>

<!-- ═══════════════════════════════════════════════════════════════════════════
     LOYALTY ROI CALCULATOR
════════════════════════════════════════════════════════════════════════════ -->
<div class="gt-card gt-animate-in">
    <div class="gt-card-header">
        <h2 class="gt-card-title">📊 Loyalty ROI Calculator</h2>
        <span style="font-size:12px;color:var(--gt-subtle)">Estimate incremental revenue from your loyalty program</span>
    </div>
    <div style="display:grid;grid-template-columns:1fr 1fr;gap:20px">
        <div>
            <div style="display:flex;flex-direction:column;gap:12px">
                <?php
                $calc_inputs = [
                    ['gt-la-calc-vip', 'VIP Customer Count', $kpi['vip_count']??0, ''],
                    ['gt-la-calc-ltv-vip', 'Avg VIP LTV ($)', round($kpi['avg_ltv_vip']??0,0), ''],
                    ['gt-la-calc-ltv-all', 'Avg All-Customer LTV ($)', round($kpi['avg_ltv_all']??0,0), ''],
                    ['gt-la-calc-disc', 'Avg Discount per VIP ($)', 15, 'Total discounts given to retain VIP'],
                ];
                foreach ($calc_inputs as $inp) : ?>
                <div>
                    <label style="font-size:11px;color:var(--gt-subtle);font-weight:600;display:block;margin-bottom:4px">
                        <?php echo esc_html($inp[1]); ?>
                    </label>
                    <input type="number" id="<?php echo esc_attr($inp[0]); ?>"
                           class="gt-input" value="<?php echo esc_attr((string)$inp[2]); ?>"
                           oninput="gtLaCalcROI()" step="0.01" min="0">
                    <?php if ($inp[3]) : ?>
                    <div style="font-size:10px;color:var(--gt-subtle);margin-top:2px"><?php echo esc_html($inp[3]); ?></div>
                    <?php endif; ?>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
        <div style="display:grid;grid-template-columns:1fr 1fr;gap:10px;align-content:start">
            <?php
            $roi_cells = [
                ['gt-la-roi-lift',   'Incremental Lift per VIP', '#22c55e'],
                ['gt-la-roi-total',  'Total Revenue Lift',       '#f59e0b'],
                ['gt-la-roi-net',    'Net ROI (after discounts)', '#22c55e'],
                ['gt-la-roi-mult',   'LTV Multiplier',           '#3b82f6'],
            ];
            foreach ($roi_cells as $rc) : ?>
            <div style="background:rgba(255,255,255,0.02);border:1px solid var(--gt-border);border-radius:8px;padding:14px;text-align:center">
                <div style="font-size:20px;font-weight:900;color:<?php echo esc_attr($rc[2]); ?>" id="<?php echo esc_attr($rc[0]); ?>">—</div>
                <div style="font-size:10px;color:var(--gt-subtle);font-weight:600;text-transform:uppercase;letter-spacing:.08em;margin-top:4px">
                    <?php echo esc_html($rc[1]); ?>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>
</div>

<?php endif; // has_prof ?>

<!-- ═══════════════════════════════════════════════════════════════════════════
     JAVASCRIPT
════════════════════════════════════════════════════════════════════════════ -->
<script>
(function(){
'use strict';

/* ── Charts ──────────────────────────────────────────────────────────── */
document.addEventListener('DOMContentLoaded', function() {
    /* Order frequency bar */
    var odCtx = document.getElementById('gt-la-order-chart');
    if (odCtx) {
        new Chart(odCtx.getContext('2d'), {
            type: 'bar',
            data: {
                labels: <?php echo $od_labels; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>,
                datasets: [{ label:'Customers', data:<?php echo $od_data; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>, backgroundColor:'rgba(59,130,246,0.6)', borderColor:'#3b82f6', borderWidth:1, borderRadius:4 }]
            },
            options: { responsive:true, maintainAspectRatio:false, plugins:{legend:{display:false}},
                       scales:{ x:{grid:{color:'rgba(255,255,255,0.04)'},ticks:{color:'#475569',font:{size:10}}},
                                y:{grid:{color:'rgba(255,255,255,0.04)'},ticks:{color:'#475569',font:{size:10}}} } }
        });
    }

    /* LTV by tier bar */
    var ltvCtx = document.getElementById('gt-la-ltv-chart');
    if (ltvCtx) {
        new Chart(ltvCtx.getContext('2d'), {
            type: 'bar',
            data: {
                labels: <?php echo $tier_chart_labels; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>,
                datasets: [{ label:'Avg LTV ($)', data:<?php echo $tier_chart_data; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>, backgroundColor:<?php echo $tier_chart_colors; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>, borderWidth:0, borderRadius:4 }]
            },
            options: { responsive:true, maintainAspectRatio:false, plugins:{legend:{display:false}},
                       scales:{ x:{grid:{display:false},ticks:{color:'#475569',font:{size:10}}},
                                y:{grid:{color:'rgba(255,255,255,0.04)'},ticks:{color:'#475569',font:{size:10},callback:function(v){return '$'+v.toLocaleString();}}} } }
        });
    }

    /* Animate funnel bars */
    document.querySelectorAll('[style*="transition:width"]').forEach(function(el) {
        var w = el.style.width; el.style.width='0%';
        setTimeout(function(){ el.style.width=w; }, 200);
    });

    /* Initial ROI calc */
    gtLaCalcROI();
});

/* ── Manual tier override ────────────────────────────────────────────── */
window.gtLaSetTier = function(nonce) {
    var search = document.getElementById('gt-la-cust-search')?.value.trim();
    var tier   = document.getElementById('gt-la-tier-select')?.value;
    var result = document.getElementById('gt-la-override-result');
    if (!search || !tier) { alert('Enter a customer ID or email and select a tier.'); return; }

    var fd = new FormData();
    fd.append('action',   'gtbogo_la_set_tier');
    fd.append('nonce',    nonce);
    fd.append('customer', search);
    fd.append('tier',     tier);

    fetch(ajaxurl,{method:'POST',body:fd})
        .then(function(r){return r.json();})
        .then(function(resp){
            if (!result) return;
            var ok = resp.success;
            result.style.cssText = 'display:block;background:' + (ok?'rgba(34,197,94,0.08)':'rgba(239,68,68,0.08)') +
                ';border:1px solid ' + (ok?'rgba(34,197,94,0.05)':'rgba(239,68,68,0.25)') +
                ';color:' + (ok?'#86efac':'#fca5a5') + ';padding:10px 12px;border-radius:7px;font-size:12px';
            result.textContent = resp.data || (ok ? 'Tier updated.' : 'Failed.');
        })
        .catch(function(){
            if(result) result.textContent='Network error.';
        });
};

window.gtLaSearchCustomer = function() { /* real-time customer search could hook here */ };

/* ── ROI calculator ──────────────────────────────────────────────────── */
window.gtLaCalcROI = function() {
    var vips   = parseFloat(document.getElementById('gt-la-calc-vip')?.value)||0;
    var ltvVip = parseFloat(document.getElementById('gt-la-calc-ltv-vip')?.value)||0;
    var ltvAll = parseFloat(document.getElementById('gt-la-calc-ltv-all')?.value)||1;
    var disc   = parseFloat(document.getElementById('gt-la-calc-disc')?.value)||0;

    var lift     = Math.max(0, ltvVip - ltvAll);
    var totalRev = lift * vips;
    var totalDisc= disc * vips;
    var net      = totalRev - totalDisc;
    var mult     = ltvAll > 0 ? (ltvVip / ltvAll).toFixed(1) : '—';

    function fmt(v) { return '$' + Math.round(v).toLocaleString(); }
    function setEl(id, val) { var el=document.getElementById(id); if(el) el.textContent=val; }

    setEl('gt-la-roi-lift',  fmt(lift));
    setEl('gt-la-roi-total', fmt(totalRev));
    setEl('gt-la-roi-net',   fmt(net));
    setEl('gt-la-roi-mult',  mult + '×');

    var netEl = document.getElementById('gt-la-roi-net');
    if (netEl) netEl.style.color = net >= 0 ? '#22c55e' : '#ef4444';
};

})();
</script>

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