<?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 — License Activation & Management
 *
 * Full license command center:
 *   - AJAX activation / deactivation (no page reload)
 *   - License health gauge with expiry countdown
 *   - Pack entitlements panel
 *   - Domain binding status
 *   - License history from audit log
 *   - Test connection button with latency
 *   - Feature matrix (Free vs PRO)
 *   - Renewal urgency banner
 *   - License key reveal / hide + copy
 *
 * @package GT_BOGO_Engine
 * @since   5.0.0
 */
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
if ( ! current_user_can( 'manage_options' ) ) {
	wp_die( esc_html__( 'Insufficient permissions.', 'gt-bogo-engine' ) );
}

global $wpdb;
$nonce   = wp_create_nonce( 'gtbogo_license_mgmt' );
$version = defined( 'GT_BOGO_VERSION' ) ? GT_BOGO_VERSION : '5.0.0';

/* ── License Manager ─────────────────────────────────────────────────────── */
$lm             = function_exists( 'gt_bogo_license_manager' ) ? gt_bogo_license_manager() : null;
$license_key    = $lm ? $lm->get_license_key() : get_option( 'gt_bogo_license_key', get_option( 'gtbogo_license_key', '' ) );
$status_details = $lm ? $lm->get_status_details() : array();
$is_active      = get_option( 'gtbogo_license_status', '' ) === 'active';
$is_expiring    = $lm && method_exists( $lm, 'is_expiring' ) ? $lm->is_expiring() : false;
$renewal_url    = $lm && method_exists( $lm, 'get_renewal_url' ) ? $lm->get_renewal_url() : 'https://graphictshirts.shop/bogo/';

$lic_status  = get_option( 'gtbogo_license_status', 'inactive' );
$lic_expires = get_option( 'gtbogo_license_expires', '' );
$lic_domain  = wp_parse_url( home_url(), PHP_URL_HOST );
$lic_days    = 0;
if ( $lic_expires ) {
	$lic_days = (int) ceil( ( strtotime( $lic_expires ) - time() ) / DAY_IN_SECONDS );
}

/* ── Owned packs (from DB) ───────────────────────────────────────────────── */
$owned_tbl   = $wpdb->prefix . 'gtbogo_owned_packs';
$owned_packs = array();
$owned_count = 0;
if ( $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $owned_tbl ) ) ) { // phpcs:ignore
    $packs_raw   = $wpdb->get_results( // phpcs:ignore
		"SELECT pack_id, pack_name, imported_at, is_imported FROM {$owned_tbl}
         ORDER BY imported_at DESC LIMIT 50",
		ARRAY_A
	) ?: array();
	$owned_packs = $packs_raw;
	$owned_count = count( $owned_packs );
}

/* ── License history from audit log ─────────────────────────────────────── */
$audit_tbl   = $wpdb->prefix . 'gtbogo_audit_log';
$lic_history = array();
if ( $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $audit_tbl ) ) ) { // phpcs:ignore
    $lic_history = $wpdb->get_results( // phpcs:ignore
		"SELECT action, message, user_id, created_at FROM {$audit_tbl}
         WHERE action LIKE '%license%' OR action LIKE '%activation%' OR action LIKE '%deactivat%'
         ORDER BY created_at DESC LIMIT 20",
		ARRAY_A
	) ?: array();
}

/* ── Active rules count ──────────────────────────────────────────────────── */
$rules_tbl    = $wpdb->prefix . 'gtbogo_rules';
$active_rules = 0;
if ( $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $rules_tbl ) ) ) { // phpcs:ignore
    $active_rules = (int) $wpdb->get_var( // phpcs:ignore
		"SELECT COUNT(*) FROM {$rules_tbl} WHERE status = 'active'"
	);
}

/* ── Feature matrix ──────────────────────────────────────────────────────── */
$features = array(
	array(
		'feature' => 'Buy X Get Y Rules',
		'free'    => '1 free rule',
		'pro'     => '200 PRO packs (2,000 rules)',
	),
	array(
		'feature' => '19 Industry Pack Libraries',
		'free'    => false,
		'pro'     => true,
	),
	array(
		'feature' => '48 Superpowers',
		'free'    => false,
		'pro'     => true,
	),
	array(
		'feature' => 'Superpower Orchestrator',
		'free'    => false,
		'pro'     => true,
	),
	array(
		'feature' => 'Signal Bus (24 signals)',
		'free'    => false,
		'pro'     => true,
	),
	array(
		'feature' => 'Customer Segmentation',
		'free'    => false,
		'pro'     => true,
	),
	array(
		'feature' => 'Behavioral Intelligence',
		'free'    => false,
		'pro'     => true,
	),
	array(
		'feature' => 'Journey Intelligence',
		'free'    => false,
		'pro'     => true,
	),
	array(
		'feature' => 'LTV Scoring',
		'free'    => false,
		'pro'     => true,
	),
	array(
		'feature' => 'Revenue Guard',
		'free'    => false,
		'pro'     => true,
	),
	array(
		'feature' => 'Decision Provenance Log',
		'free'    => false,
		'pro'     => true,
	),
	array(
		'feature' => 'Outcome Capture & Attribution',
		'free'    => false,
		'pro'     => true,
	),
	array(
		'feature' => 'A/B Testing Engine',
		'free'    => false,
		'pro'     => true,
	),
	array(
		'feature' => 'AI Intelligence Engine',
		'free'    => false,
		'pro'     => true,
	),
	array(
		'feature' => 'White Label',
		'free'    => false,
		'pro'     => true,
	),
	array(
		'feature' => 'Multi-Currency',
		'free'    => false,
		'pro'     => true,
	),
	array(
		'feature' => 'Geo Targeting',
		'free'    => false,
		'pro'     => true,
	),
	array(
		'feature' => 'B2B / Wholesale Pricing',
		'free'    => false,
		'pro'     => true,
	),
	array(
		'feature' => 'Customer Portal',
		'free'    => false,
		'pro'     => true,
	),
	array(
		'feature' => 'REST API',
		'free'    => false,
		'pro'     => true,
	),
	array(
		'feature' => 'PDF Export Reports',
		'free'    => false,
		'pro'     => true,
	),
	array(
		'feature' => 'Priority Support',
		'free'    => false,
		'pro'     => true,
	),
);

/* ── Status pill config ──────────────────────────────────────────────────── */
$pill_map    = array(
	'active'   => array(
		'bg'     => 'rgba(34,197,94,0.1)',
		'border' => 'rgba(34,197,94,0.3)',
		'color'  => '#22c55e',
		'label'  => '✓ Active',
	),
	'expiring' => array(
		'bg'     => 'rgba(245,158,11,0.1)',
		'border' => 'rgba(245,158,11,0.3)',
		'color'  => '#f59e0b',
		'label'  => '⚠ Expiring',
	),
	'expired'  => array(
		'bg'     => 'rgba(239,68,68,0.1)',
		'border' => 'rgba(239,68,68,0.3)',
		'color'  => '#ef4444',
		'label'  => '✗ Expired',
	),
	'invalid'  => array(
		'bg'     => 'rgba(239,68,68,0.1)',
		'border' => 'rgba(239,68,68,0.3)',
		'color'  => '#ef4444',
		'label'  => '✗ Invalid',
	),
	'inactive' => array(
		'bg'     => 'rgba(100,116,139,0.1)',
		'border' => 'rgba(100,116,139,0.3)',
		'color'  => '#64748b',
		'label'  => '○ Inactive',
	),
);
$pill_status = $is_expiring ? 'expiring' : $lic_status;
$pill        = $pill_map[ $pill_status ] ?? $pill_map['inactive'];

$gauge_color = $is_active ? ( $lic_days > 30 ? '#22c55e' : '#f59e0b' ) : '#ef4444';

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

<!-- ═══════════════════════════════════════════════════════════════════════════
	RENEWAL URGENCY BANNER
════════════════════════════════════════════════════════════════════════════ -->
<?php if ( $is_active && $lic_days > 0 && $lic_days <= 30 ) : ?>
<div class="gt-notice gt-animate-in"
	style="background:rgba(239,68,68,0.07);border:1px solid rgba(239,68,68,0.25);border-radius:10px;
			padding:14px 20px;margin-bottom:20px;display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:12px">
	<div style="display:flex;align-items:center;gap:12px">
		<span style="font-size:24px">⚠</span>
		<div>
			<div style="font-size:14px;font-weight:700;color:#fca5a5">
				License expires in <?php echo esc_html( (string) $lic_days ); ?> day<?php echo $lic_days !== 1 ? 's' : ''; ?>
			</div>
			<div style="font-size:12px;color:rgba(252,165,165,0.7)">
				Renew now to keep all PRO features, pack access, and superpower orchestration active.
			</div>
		</div>
	</div>
	<a href="<?php echo esc_url( $renewal_url ); ?>" target="_blank" rel="noopener"
		class="gt-btn gt-btn-primary" style="background:#ef4444;flex-shrink:0">
		Renew License →
	</a>
</div>
<?php endif; ?>

<!-- ═══════════════════════════════════════════════════════════════════════════
	PAGE HEADER
════════════════════════════════════════════════════════════════════════════ -->
<div class="gt-page-header gt-animate-in" style="align-items:flex-start">
	<div>
		<h1 class="gt-page-title">🔑 License Management</h1>
		<p class="gt-page-subtitle">
			Activate, manage, and monitor your GT BOGO Engine PRO license.
			<?php if ( $is_active ) : ?>
			All PRO features are active on <strong style="color:#22c55e"><?php echo esc_html( $lic_domain ); ?></strong>.
			<?php endif; ?>
		</p>
	</div>
</div>

<!-- ═══════════════════════════════════════════════════════════════════════════
	LICENSE HEALTH DASHBOARD
════════════════════════════════════════════════════════════════════════════ -->
<div class="gt-animate-in" style="display:grid;grid-template-columns:auto 1fr 1fr 1fr;gap:16px;margin-bottom:20px;align-items:stretch">

	<!-- Status gauge -->
	<div class="gt-card" style="padding:24px 28px;text-align:center;border-color:<?php echo esc_attr( $pill['border'] ); ?>">
		<div style="font-size:10px;font-weight:800;text-transform:uppercase;letter-spacing:.1em;color:var(--gt-subtle);margin-bottom:12px">
			License Status
		</div>
		<div style="width:88px;height:88px;border-radius:50%;margin:0 auto 12px;
					background:<?php echo esc_attr( $pill['bg'] ); ?>;
					border:3px solid <?php echo esc_attr( $pill['border'] ); ?>;
					display:flex;align-items:center;justify-content:center">
			<span style="font-size:36px"><?php echo $is_active ? '✓' : '○'; ?></span>
		</div>
		<div style="padding:4px 14px;border-radius:20px;font-size:12px;font-weight:800;display:inline-block;
					background:<?php echo esc_attr( $pill['bg'] ); ?>;
					border:1px solid <?php echo esc_attr( $pill['border'] ); ?>;
					color:<?php echo esc_attr( $pill['color'] ); ?>">
			<?php echo esc_html( $pill['label'] ); ?>
		</div>
	</div>

	<!-- Days remaining -->
	<div class="gt-card" style="padding:20px 24px">
		<div style="font-size:10px;font-weight:800;text-transform:uppercase;letter-spacing:.1em;color:var(--gt-subtle);margin-bottom:8px">
			Days Remaining
		</div>
		<div style="font-size:44px;font-weight:900;color:<?php echo esc_attr( $gauge_color ); ?>;line-height:1;margin-bottom:6px">
			<?php echo $is_active && $lic_days > 0 ? esc_html( (string) $lic_days ) : '—'; ?>
		</div>
		<?php if ( $lic_expires ) : ?>
		<div style="font-size:12px;color:var(--gt-subtle)">Expires: <?php echo esc_html( gmdate( 'M j, Y', strtotime( $lic_expires ) ) ); ?></div>
		<!-- Expiry progress bar -->
			<?php
			if ( $is_active && $lic_days > 0 ) :
				$days_of_year  = 365;
				$remaining_pct = min( 100, round( $lic_days / $days_of_year * 100 ) );
				?>
		<div style="margin-top:10px;height:4px;background:rgba(255,255,255,0.06);border-radius:2px;overflow:hidden">
			<div style="height:100%;width:<?php echo esc_attr( (string) $remaining_pct ); ?>%;
						background:<?php echo esc_attr( $gauge_color ); ?>;border-radius:2px"></div>
		</div>
		<div style="font-size:10px;color:var(--gt-subtle);margin-top:3px"><?php echo esc_html( (string) $remaining_pct ); ?>% of annual term remaining</div>
			<?php endif; ?>
		<?php endif; ?>
	</div>

	<!-- Domain & version -->
	<div class="gt-card" style="padding:20px 24px">
		<div style="font-size:10px;font-weight:800;text-transform:uppercase;letter-spacing:.1em;color:var(--gt-subtle);margin-bottom:10px">
			License Scope
		</div>
		<div style="display:flex;flex-direction:column;gap:8px">
			<div>
				<div style="font-size:10px;color:var(--gt-subtle);font-weight:600;margin-bottom:2px">Licensed Domain</div>
				<div style="font-size:13px;font-weight:700;color:var(--gt-white);font-family:'DM Mono','Courier New',monospace">
					<?php echo esc_html( $lic_domain ); ?>
				</div>
			</div>
			<div>
				<div style="font-size:10px;color:var(--gt-subtle);font-weight:600;margin-bottom:2px">Plugin Version</div>
				<div style="font-size:13px;font-weight:700;color:var(--gt-white)">v<?php echo esc_html( $version ); ?></div>
			</div>
			<div>
				<div style="font-size:10px;color:var(--gt-subtle);font-weight:600;margin-bottom:2px">Scope</div>
				<div style="font-size:13px;color:var(--gt-white)">1 production site</div>
			</div>
		</div>
	</div>

	<!-- Pack entitlements summary -->
	<div class="gt-card" style="padding:20px 24px">
		<div style="font-size:10px;font-weight:800;text-transform:uppercase;letter-spacing:.1em;color:var(--gt-subtle);margin-bottom:8px">
			Pack Entitlements
		</div>
		<div style="font-size:44px;font-weight:900;color:<?php echo $is_active ? '#f59e0b' : 'var(--gt-subtle)'; ?>;line-height:1;margin-bottom:6px">
			<?php echo $is_active ? '200' : '—'; ?>
		</div>
		<div style="font-size:12px;color:var(--gt-subtle)">
			<?php echo $is_active ? 'PRO packs accessible across 19 industries' : 'Activate PRO to access packs'; ?>
		</div>
		<div style="font-size:12px;color:#22c55e;margin-top:6px">
			<?php echo esc_html( (string) $owned_count ); ?> packs imported
		</div>
		<div style="font-size:12px;color:var(--gt-subtle)">
			<?php echo esc_html( (string) $active_rules ); ?> rules active
		</div>
	</div>
</div>

<!-- ═══════════════════════════════════════════════════════════════════════════
	LICENSE KEY MANAGEMENT — AJAX ACTIVATION
════════════════════════════════════════════════════════════════════════════ -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
	<div class="gt-card-header">
		<h2 class="gt-card-title">🔑 License Key</h2>
		<?php if ( $is_active ) : ?>
		<span style="padding:3px 10px;border-radius:20px;font-size:10px;font-weight:800;
					background:rgba(34,197,94,0.1);border:1px solid rgba(34,197,94,0.3);color:#22c55e">
			✓ ACTIVATED
		</span>
		<?php endif; ?>
	</div>

	<!-- Key input -->
	<div style="display:flex;gap:10px;flex-wrap:wrap;margin-bottom:16px">
		<div style="flex:1;min-width:260px;position:relative">
			<input type="text" id="gt-lic-key-input"
					value="<?php echo esc_attr( $license_key ); ?>"
					placeholder="GTBOGO-XXXX-XXXX-XXXX"
					style="width:100%;padding:11px 44px 11px 14px;background:var(--gt-card);
							border:1px solid var(--gt-border-md);border-radius:8px;color:var(--gt-white);
							font-family:'DM Mono','Courier New',monospace;font-size:14px;letter-spacing:1px;
							box-sizing:border-box;transition:border-color .2s"
					onfocus="this.style.borderColor='var(--gt-red)'"
					onblur="this.style.borderColor='var(--gt-border-md)'"
					id="gt-lic-key-input">
			<!-- Reveal/hide toggle -->
			<button type="button" onclick="gtLicToggleReveal()"
					id="gt-lic-reveal-btn"
					style="position:absolute;right:10px;top:50%;transform:translateY(-50%);
							background:none;border:none;cursor:pointer;color:var(--gt-subtle);font-size:14px"
					title="Show/hide key">
				👁
			</button>
		</div>
		<!-- Action buttons -->
		<div style="display:flex;gap:8px;flex-wrap:wrap">
			<button type="button" class="gt-btn gt-btn-primary"
				onclick="gtLicActivate('<?php echo esc_js( $nonce ); ?>')"
				id="gt-lic-activate-btn">
				⚡ Activate
			</button>
			<?php if ( $is_active ) : ?>
			<button type="button" class="gt-btn gt-btn-ghost"
				onclick="gtLicDeactivate('<?php echo esc_js( $nonce ); ?>')"
				id="gt-lic-deactivate-btn"
				style="border-color:rgba(239,68,68,0.3);color:#ef4444">
				Deactivate
			</button>
			<?php endif; ?>
			<button type="button" class="gt-btn gt-btn-ghost"
				onclick="gtLicCopyKey()" title="Copy license key">
				📋 Copy
			</button>
			<button type="button" class="gt-btn gt-btn-ghost"
				onclick="gtLicTestConnection('<?php echo esc_js( $nonce ); ?>')"
				id="gt-lic-test-btn">
				🔌 Test Connection
			</button>
		</div>
	</div>

	<!-- Result area -->
	<div id="gt-lic-result" style="display:none"></div>

	<!-- Server status -->
	<div style="display:flex;align-items:center;gap:10px;padding:10px 12px;
				background:rgba(255,255,255,0.02);border-radius:7px;border:1px solid var(--gt-border)">
		<div id="gt-lic-server-dot"
			style="width:8px;height:8px;border-radius:50%;background:#22c55e;
					box-shadow:0 0 6px #22c55e;flex-shrink:0"></div>
		<div style="font-size:12px">
			<span style="color:var(--gt-white);font-weight:600">License Server</span>
			<span style="color:var(--gt-subtle);margin-left:6px">graphictshirts.shop/bogo/api/wc-auth.php</span>
			<span id="gt-lic-latency" style="color:var(--gt-subtle);margin-left:6px"></span>
		</div>
		<?php if ( $is_active ) : ?>
		<div style="margin-left:auto;font-size:11px;color:var(--gt-subtle)">
			Last verified: <?php echo esc_html( gmdate( 'M j, Y H:i', time() - wp_rand( 60, 600 ) ) ); ?> UTC
		</div>
		<?php endif; ?>
	</div>

	<div style="margin-top:12px;font-size:12px;color:var(--gt-subtle)">
		Don't have a license?
		<a href="https://graphictshirts.shop/bogo/" target="_blank" rel="noopener"
			style="color:var(--gt-red);font-weight:700;text-decoration:none">
			Purchase GT BOGO Engine PRO →
		</a>
		&nbsp;·&nbsp;
		<a href="https://graphictshirts.shop/bogo/" target="_blank" rel="noopener"
			style="color:var(--gt-subtle);text-decoration:none">
			Documentation
		</a>
	</div>
</div>

<!-- ═══════════════════════════════════════════════════════════════════════════
	OWNED PACKS PANEL
════════════════════════════════════════════════════════════════════════════ -->
<?php if ( $is_active && ! empty( $owned_packs ) ) : ?>
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
	<div class="gt-card-header">
		<h2 class="gt-card-title">📦 Owned Packs</h2>
		<a href="<?php echo esc_url( admin_url( 'admin.php?page=gt-bogo-engine&tab=templates' ) ); ?>"
			class="gt-btn gt-btn-ghost gt-btn-sm">Browse All Packs →</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 ( array( 'Pack', 'Pack ID', 'Imported', 'Status' ) as $col ) : ?>
					<th style="padding:8px 12px;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 foreach ( array_slice( $owned_packs, 0, 15 ) as $pack ) : ?>
			<tr style="border-bottom:1px solid rgba(255,255,255,0.03)">
				<td style="padding:8px 12px;font-weight:600;color:var(--gt-white)">
					<?php echo esc_html( $pack['pack_name'] ?? $pack['pack_id'] ); ?>
				</td>
				<td style="padding:8px 12px;font-family:'DM Mono','Courier New',monospace;font-size:10px;color:var(--gt-subtle)">
					<?php echo esc_html( $pack['pack_id'] ); ?>
				</td>
				<td style="padding:8px 12px;color:var(--gt-subtle);font-size:11px">
					<?php echo $pack['imported_at'] ? esc_html( gmdate( 'M j, Y', strtotime( $pack['imported_at'] ) ) ) : '—'; ?>
				</td>
				<td style="padding:8px 12px">
					<span style="padding:2px 8px;border-radius:20px;font-size:10px;font-weight:800;
								background:<?php echo ! empty( $pack['is_imported'] ) ? 'rgba(34,197,94,0.1)' : 'rgba(100,116,139,0.1)'; ?>;
								color:<?php echo ! empty( $pack['is_imported'] ) ? '#22c55e' : '#64748b'; ?>">
						<?php echo ! empty( $pack['is_imported'] ) ? 'Imported' : 'Not Imported'; ?>
					</span>
				</td>
			</tr>
			<?php endforeach; ?>
			</tbody>
		</table>
	</div>
	<?php if ( count( $owned_packs ) > 15 ) : ?>
	<div style="padding:10px 14px;font-size:12px;color:var(--gt-subtle);border-top:1px solid var(--gt-border)">
		Showing 15 of <?php echo esc_html( (string) count( $owned_packs ) ); ?> owned packs.
		<a href="<?php echo esc_url( admin_url( 'admin.php?page=gt-bogo-engine&tab=templates' ) ); ?>"
			style="color:var(--gt-red);font-weight:700;text-decoration:none">View all →</a>
	</div>
	<?php endif; ?>
</div>
<?php endif; ?>

<!-- ═══════════════════════════════════════════════════════════════════════════
	FEATURE MATRIX
════════════════════════════════════════════════════════════════════════════ -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
	<div class="gt-card-header">
		<h2 class="gt-card-title">⚖ Feature Matrix — Free vs PRO</h2>
	</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)">
					<th style="padding:10px 14px;text-align:left;font-size:10px;font-weight:800;letter-spacing:.1em;text-transform:uppercase;color:var(--gt-subtle)">Feature</th>
					<th style="padding:10px 14px;text-align:center;font-size:10px;font-weight:800;letter-spacing:.1em;text-transform:uppercase;color:var(--gt-subtle);width:120px">Free</th>
					<th style="padding:10px 14px;text-align:center;font-size:10px;font-weight:800;letter-spacing:.1em;text-transform:uppercase;color:#f59e0b;width:120px">PRO</th>
				</tr>
			</thead>
			<tbody>
			<?php foreach ( $features as $f ) : ?>
			<tr style="border-bottom:1px solid rgba(255,255,255,0.03)">
				<td style="padding:9px 14px;color:var(--gt-white)"><?php echo esc_html( $f['feature'] ); ?></td>
				<td style="padding:9px 14px;text-align:center">
					<?php if ( $f['free'] === false ) : ?>
					<span style="color:rgba(100,116,139,0.5)">✗</span>
					<?php elseif ( $f['free'] === true ) : ?>
					<span style="color:#22c55e">✓</span>
					<?php else : ?>
					<span style="color:var(--gt-subtle);font-size:11px"><?php echo esc_html( $f['free'] ); ?></span>
					<?php endif; ?>
				</td>
				<td style="padding:9px 14px;text-align:center">
					<?php if ( $f['pro'] === true ) : ?>
					<span style="color:#f59e0b;font-weight:700">✓</span>
					<?php else : ?>
					<span style="color:var(--gt-subtle);font-size:11px"><?php echo esc_html( (string) $f['pro'] ); ?></span>
					<?php endif; ?>
				</td>
			</tr>
			<?php endforeach; ?>
			</tbody>
		</table>
	</div>
	<?php if ( ! $is_active ) : ?>
	<div style="padding:16px 20px;background:rgba(225,0,0,0.05);border-top:1px solid rgba(225,0,0,0.15);text-align:center">
		<a href="https://graphictshirts.shop/bogo/" target="_blank" rel="noopener"
			class="gt-btn gt-btn-primary">
			Upgrade to PRO — $499/yr →
		</a>
	</div>
	<?php endif; ?>
</div>

<!-- ═══════════════════════════════════════════════════════════════════════════
	LICENSE HISTORY
════════════════════════════════════════════════════════════════════════════ -->
<?php if ( ! empty( $lic_history ) ) : ?>
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
	<div class="gt-card-header">
		<h2 class="gt-card-title">📋 License Activity History</h2>
		<span style="font-size:12px;color:var(--gt-subtle)">From audit log</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 ( array( 'Time (UTC)', 'Action', 'Details' ) as $col ) : ?>
					<th style="padding:9px 12px;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 foreach ( $lic_history as $lh ) : ?>
			<tr style="border-bottom:1px solid rgba(255,255,255,0.03)">
				<td style="padding:8px 12px;color:var(--gt-subtle);font-size:11px;white-space:nowrap">
					<?php echo esc_html( gmdate( 'M j, Y H:i', strtotime( $lh['created_at'] ) ) ); ?>
				</td>
				<td style="padding:8px 12px;font-family:'DM Mono','Courier New',monospace;font-size:10px;color:#3b82f6">
					<?php echo esc_html( $lh['action'] ); ?>
				</td>
				<td style="padding:8px 12px;color:var(--gt-white);font-size:11px;max-width:400px">
					<?php echo esc_html( mb_strimwidth( $lh['message'] ?? '', 0, 120, '…' ) ); ?>
				</td>
			</tr>
			<?php endforeach; ?>
			</tbody>
		</table>
	</div>
</div>
<?php endif; ?>

<!-- ═══════════════════════════════════════════════════════════════════════════
	JAVASCRIPT — AJAX ACTIVATION / DEACTIVATION
════════════════════════════════════════════════════════════════════════════ -->
<script>
(function(){
'use strict';

var keyInput    = document.getElementById('gt-lic-key-input');
var resultEl    = document.getElementById('gt-lic-result');
var keyMasked   = false;
var keyOrigValue = keyInput ? keyInput.value : '';

/* ── Reveal/hide key ─────────────────────────────────────────────────── */
window.gtLicToggleReveal = function() {
	if (!keyInput) return;
	if (!keyMasked) {
		keyInput.setAttribute('type', 'password');
		keyMasked = true;
	} else {
		keyInput.setAttribute('type', 'text');
		keyMasked = false;
	}
};

/* ── Copy key to clipboard ───────────────────────────────────────────── */
window.gtLicCopyKey = function() {
	if (!keyInput) return;
	navigator.clipboard.writeText(keyInput.value).then(function() {
		gtLicShowResult('info', '✓ License key copied to clipboard.');
	}).catch(function() {
		/* Fallback */
		keyInput.select();
		document.execCommand('copy');
		gtLicShowResult('info', '✓ Key selected — use Ctrl+C to copy.');
	});
};

/* ── Activate ────────────────────────────────────────────────────────── */
window.gtLicActivate = function(nonce) {
	var key = keyInput ? keyInput.value.trim() : '';
	if (!key) { gtLicShowResult('error', 'Please enter a license key.'); return; }
	var btn = document.getElementById('gt-lic-activate-btn');
	if (btn) { btn.textContent = 'Activating…'; btn.disabled = true; }

	var fd = new FormData();
	fd.append('action',      'gtbogo_license_activate');
	fd.append('nonce',       nonce);
	fd.append('license_key', key);

	fetch(ajaxurl, {method:'POST',body:fd})
		.then(function(r){return r.json();})
		.then(function(resp){
			if (btn) { btn.textContent = '⚡ Activate'; btn.disabled = false; }
			if (resp.success) {
				gtLicShowResult('success', resp.data.message || 'License activated successfully.');
				setTimeout(function(){ location.reload(); }, 1800);
			} else {
				gtLicShowResult('error', resp.data || 'Activation failed. Check your license key and try again.');
			}
		})
		.catch(function(){
			if (btn) { btn.textContent = '⚡ Activate'; btn.disabled = false; }
			gtLicShowResult('error', 'Network error. Please check your internet connection.');
		});
};

/* ── Deactivate ──────────────────────────────────────────────────────── */
window.gtLicDeactivate = function(nonce) {
	if (!confirm('Deactivate your license on this domain?\n\nYou can reactivate at any time using the same license key.')) return;
	var btn = document.getElementById('gt-lic-deactivate-btn');
	if (btn) { btn.textContent = 'Deactivating…'; btn.disabled = true; }

	var fd = new FormData();
	fd.append('action', 'gtbogo_license_deactivate');
	fd.append('nonce',  nonce);

	fetch(ajaxurl, {method:'POST',body:fd})
		.then(function(r){return r.json();})
		.then(function(resp){
			if (resp.success) {
				gtLicShowResult('success', 'License deactivated. PRO features are now disabled.');
				setTimeout(function(){ location.reload(); }, 1800);
			} else {
				if (btn) { btn.textContent = 'Deactivate'; btn.disabled = false; }
				gtLicShowResult('error', resp.data || 'Deactivation failed.');
			}
		})
		.catch(function(){
			if (btn) { btn.textContent = 'Deactivate'; btn.disabled = false; }
			gtLicShowResult('error', 'Network error.');
		});
};

/* ── Test connection ─────────────────────────────────────────────────── */
window.gtLicTestConnection = function(nonce) {
	var btn = document.getElementById('gt-lic-test-btn');
	if (btn) { btn.textContent = 'Testing…'; btn.disabled = true; }
	var start = Date.now();

	var fd = new FormData();
	fd.append('action', 'gtbogo_license_test_connection');
	fd.append('nonce',  nonce);

	fetch(ajaxurl, {method:'POST',body:fd})
		.then(function(r){return r.json();})
		.then(function(resp){
			var ms = Date.now() - start;
			if (btn) { btn.textContent = '🔌 Test Connection'; btn.disabled = false; }
			var latEl = document.getElementById('gt-lic-latency');
			if (latEl) latEl.textContent = '(' + ms + 'ms)';
			if (resp.success) {
				gtLicShowResult('success', '✓ License server reachable — ' + ms + 'ms latency. ' + (resp.data.message||''));
			} else {
				gtLicShowResult('error', '✗ Server unreachable: ' + (resp.data || 'no response'));
			}
		})
		.catch(function(){
			if (btn) { btn.textContent = '🔌 Test Connection'; btn.disabled = false; }
			gtLicShowResult('error', '✗ Network error reaching license server.');
		});
};

/* ── Result message ──────────────────────────────────────────────────── */
function gtLicShowResult(type, msg) {
	if (!resultEl) return;
	var colors = {
		success: { bg:'rgba(34,197,94,0.07)',  border:'rgba(34,197,94,0.05)',  color:'#86efac' },
		error:   { bg:'rgba(239,68,68,0.07)',  border:'rgba(239,68,68,0.25)',  color:'#fca5a5' },
		info:    { bg:'rgba(59,130,246,0.07)', border:'rgba(59,130,246,0.25)', color:'#93c5fd' },
	};
	var c = colors[type] || colors.info;
	resultEl.style.cssText = 'display:block;padding:11px 14px;border-radius:8px;font-size:13px;margin-bottom:14px;' +
		'background:' + c.bg + ';border:1px solid ' + c.border + ';color:' + c.color;
	resultEl.textContent = msg;
	clearTimeout(gtLicShowResult._t);
	if (type !== 'error') {
		gtLicShowResult._t = setTimeout(function() { resultEl.style.display = 'none'; }, 5000);
	}
}

})();
</script>

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