<?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 Management (Full Page)
 *
 * The comprehensive license management page (distinct from page-settings-license.php
 * which is the tab quick-access):
 *   - Full AJAX activation / deactivation
 *   - License health score gauge + expiry countdown
 *   - Domain registration + multi-site entitlements
 *   - Pack entitlements summary with import count
 *   - License history log from audit table
 *   - Test connection button with latency display
 *   - Server status indicator
 *   - Complete Free vs PRO feature matrix
 *   - License key reveal / hide + clipboard copy
 *   - Renewal urgency banner
 *   - License notes / download receipt link
 *   - PayPal IPN license delivery status
 *
 * @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;

$version = defined( 'GT_BOGO_VERSION' ) ? GT_BOGO_VERSION : '5.0.0';
$nonce   = wp_create_nonce( 'gtbogo_license_full' );
$is_pro  = function_exists( 'gt_bogo_has_pro' ) ? gt_bogo_has_pro() : false;

/* ── License data ────────────────────────────────────────────────────────── */
$lm          = ( class_exists( 'GT_BOGO_License_Manager' ) ) ? GT_BOGO_License_Manager::instance() : null;
$license_key = $lm ? $lm->get_license_key() : get_option( 'gt_bogo_license_key', get_option( 'gtbogo_license_key', '' ) );
$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 );
$renewal_url = 'https://graphictshirts.shop/bogo/';

$lic_days = 0;
if ( $lic_expires ) {
	$lic_days = max( 0, (int) ceil( ( strtotime( $lic_expires ) - time() ) / DAY_IN_SECONDS ) );
}

$is_active   = $lic_status === 'active';
$is_expiring = $is_active && $lic_days > 0 && $lic_days <= 30;

/* ── Owned packs ────────────────────────────────────────────────────────── */
$owned_tbl      = $wpdb->prefix . 'gtbogo_owned_packs';
$owned_count    = 0;
$imported_count = 0;
if ( $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $owned_tbl ) ) ) { // phpcs:ignore
    $owned_count    = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$owned_tbl}" ); // phpcs:ignore
    $imported_count = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$owned_tbl} WHERE is_imported=1" ); // phpcs:ignore
}

/* ── Active rules ───────────────────────────────────────────────────────── */
$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( "SELECT COUNT(*) FROM {$rules_tbl} WHERE status='active'" ); // phpcs:ignore
}

/* ── License history ────────────────────────────────────────────────────── */
$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%'
         ORDER BY created_at DESC LIMIT 20",
		ARRAY_A
	) ?: array();
}

/* ── UI colours ─────────────────────────────────────────────────────────── */
$gauge_color = $is_active ? ( $lic_days > 30 ? '#22c55e' : '#f59e0b' ) : '#ef4444';
$pill_map    = array(
	'active'   => array( '#22c55e', 'rgba(34,197,94,0.1)', 'rgba(34,197,94,0.3)', '✓ Active' ),
	'expiring' => array( '#f59e0b', 'rgba(245,158,11,0.1)', 'rgba(245,158,11,0.3)', '⚠ Expiring' ),
	'inactive' => array( '#64748b', 'rgba(100,116,139,0.1)', 'rgba(100,116,139,0.2)', '○ Inactive' ),
	'expired'  => array( '#ef4444', 'rgba(239,68,68,0.1)', 'rgba(239,68,68,0.3)', '✗ Expired' ),
);
$pill_key    = $is_expiring ? 'expiring' : ( $is_active ? 'active' : $lic_status );
$pill        = $pill_map[ $pill_key ] ?? $pill_map['inactive'];

$features = array(
	array( 'Buy X Get Y Rules', '1 free rule', '200 packs × 10 rules' ),
	array( '19 Industry Pack Libraries', false, true ),
	array( '48 Superpowers', false, true ),
	array( 'Superpower Orchestrator', false, true ),
	array( 'Signal Bus (24 signals)', false, true ),
	array( 'Customer Intelligence', false, true ),
	array( 'Behavioral Intelligence', false, true ),
	array( 'Revenue Guard', false, true ),
	array( 'Decision Provenance Log', false, true ),
	array( 'Outcome Capture & Lift', false, true ),
	array( 'A/B Testing Engine', false, true ),
	array( 'AI Intelligence Engine', false, true ),
	array( 'White Label', false, true ),
	array( 'Multi-Currency / Geo', false, true ),
	array( 'REST API', false, true ),
	array( 'PDF Export Reports', false, true ),
	array( 'Priority Support', false, true ),
	array( 'Webhook Integrations', false, true ),
	array( 'Deal Lockout / Revenue Guard', false, true ),
	array( 'Loyalty Acceleration', false, true ),
);

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

<?php if ( $is_expiring ) : ?>
<div style="background:rgba(239,68,68,0.07);border:1px solid rgba(239,68,68,0.25);border-radius:10px;
			padding:12px 20px;margin-bottom:18px;display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:12px"
	class="gt-animate-in">
	<div style="font-size:13px;color:#fca5a5;font-weight:600">
		⚠ License expires in <?php echo esc_html( (string) $lic_days ); ?> day<?php echo $lic_days !== 1 ? 's' : ''; ?> — renew now to keep all PRO features
	</div>
	<a href="<?php echo esc_url( $renewal_url ); ?>" target="_blank" rel="noopener"
		class="gt-btn gt-btn-primary gt-btn-sm" style="background:#ef4444;flex-shrink:0">
		Renew License →
	</a>
</div>
<?php endif; ?>

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

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

	<!-- Status circle -->
	<div class="gt-card" style="padding:22px 26px;text-align:center;min-width:160px;border-color:<?php echo esc_attr( $pill[2] ); ?>">
		<div style="font-size:10px;font-weight:800;text-transform:uppercase;letter-spacing:.1em;color:var(--gt-subtle);margin-bottom:10px">Status</div>
		<div style="width:80px;height:80px;border-radius:50%;margin:0 auto 10px;
					background:<?php echo esc_attr( $pill[1] ); ?>;border:2px solid <?php echo esc_attr( $pill[2] ); ?>;
					display:flex;align-items:center;justify-content:center;font-size:32px">
			<?php echo $is_active ? '✓' : '○'; ?>
		</div>
		<span style="padding:3px 12px;border-radius:20px;font-size:11px;font-weight:800;display:inline-block;
					background:<?php echo esc_attr( $pill[1] ); ?>;border:1px solid <?php echo esc_attr( $pill[2] ); ?>;
					color:<?php echo esc_attr( $pill[0] ); ?>">
			<?php echo esc_html( $pill[3] ); ?>
		</span>
	</div>

	<!-- Days remaining -->
	<div class="gt-card" style="padding:20px 22px">
		<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:42px;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>
			<?php
			if ( $is_active && $lic_days > 0 ) :
				$p = min( 100, round( $lic_days / 365 * 100 ) );
				?>
		<div style="margin-top:8px;height:4px;background:rgba(255,255,255,0.06);border-radius:2px;overflow:hidden">
			<div style="height:100%;width:<?php echo esc_attr( (string) $p ); ?>%;background:<?php echo esc_attr( $gauge_color ); ?>;border-radius:2px"></div>
		</div>
			<?php endif; ?>
		<?php endif; ?>
		<div style="margin-top:8px;font-size:11px;color:var(--gt-subtle)">
			Domain: <span style="color:var(--gt-white);font-family:'DM Mono','Courier New',monospace"><?php echo esc_html( $lic_domain ); ?></span>
		</div>
	</div>

	<!-- Pack entitlements -->
	<div class="gt-card" style="padding:20px 22px">
		<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:36px;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)">packs available across 19 industries</div>
		<div style="margin-top:8px;font-size:12px;color:#22c55e"><?php echo esc_html( (string) $owned_count ); ?> owned · <?php echo esc_html( (string) $imported_count ); ?> imported</div>
		<div style="font-size:12px;color:var(--gt-subtle);margin-top:2px"><?php echo esc_html( (string) $active_rules ); ?> active rules</div>
	</div>

	<!-- Quick actions -->
	<div class="gt-card" style="padding:20px 22px">
		<div style="font-size:10px;font-weight:800;text-transform:uppercase;letter-spacing:.1em;color:var(--gt-subtle);margin-bottom:10px">Quick Actions</div>
		<div style="display:flex;flex-direction:column;gap:8px">
			<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">📦 My Packs</a>
			<a href="<?php echo esc_url( $renewal_url ); ?>" target="_blank" rel="noopener"
				class="gt-btn gt-btn-ghost gt-btn-sm">↗ Renew License</a>
			<a href="mailto:support@graphictshirts.shop"
				class="gt-btn gt-btn-ghost gt-btn-sm">✉ Support</a>
		</div>
	</div>
</div>

<!-- ═══ LICENSE KEY ══════════════════════════════════════════════════════════ -->
<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>

	<div style="display:flex;gap:10px;flex-wrap:wrap;margin-bottom:14px">
		<div style="flex:1;min-width:260px;position:relative">
			<input type="text" id="gt-lic-key"
					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"
					onfocus="this.style.borderColor='var(--gt-red)'" onblur="this.style.borderColor='var(--gt-border-md)'">
			<button type="button" onclick="gtLicToggleReveal()"
					style="position:absolute;right:10px;top:50%;transform:translateY(-50%);background:none;border:none;cursor:pointer;color:var(--gt-subtle);font-size:16px">👁</button>
		</div>
		<button type="button" class="gt-btn gt-btn-primary" onclick="gtLicActivate('<?php echo esc_js( $nonce ); ?>')">⚡ Activate</button>
		<?php if ( $is_active ) : ?>
		<button type="button" class="gt-btn gt-btn-ghost" onclick="gtLicDeactivate('<?php echo esc_js( $nonce ); ?>')"
				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()">📋 Copy</button>
		<button type="button" class="gt-btn gt-btn-ghost" onclick="gtLicTest('<?php echo esc_js( $nonce ); ?>')" id="gt-lic-test-btn">🔌 Test</button>
	</div>

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

	<div style="display:flex;align-items:center;gap:8px;padding:9px 12px;background:rgba(255,255,255,0.02);border:1px solid var(--gt-border);border-radius:7px">
		<div style="width:7px;height:7px;border-radius:50%;background:#22c55e;box-shadow:0 0 5px #22c55e;flex-shrink:0"></div>
		<div style="font-size:12px;color:var(--gt-subtle)">License server: <span style="color:var(--gt-white)">graphictshirts.shop/bogo/api/wc-auth.php</span></div>
		<span id="gt-lic-latency" style="font-size:11px;color:var(--gt-subtle);margin-left:auto"></span>
	</div>

	<div style="margin-top:10px;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 PRO — $499/yr →</a>
	</div>
</div>

<!-- ═══ FEATURE MATRIX ══════════════════════════════════════════════════════ -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
	<div class="gt-card-header"><h2 class="gt-card-title">⚖ Free vs PRO Feature Matrix</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:8px 14px;color:var(--gt-white)"><?php echo esc_html( $f[0] ); ?></td>
				<td style="padding:8px 14px;text-align:center">
					<?php if ( $f[1] === false ) : ?>
					<span style="color:rgba(100,116,139,0.5)">✗</span>
					<?php elseif ( $f[1] === true ) : ?>
					<span style="color:#22c55e">✓</span>
					<?php else : ?>
					<span style="color:var(--gt-subtle);font-size:11px"><?php echo esc_html( (string) $f[1] ); ?></span>
					<?php endif; ?>
				</td>
				<td style="padding:8px 14px;text-align:center">
					<?php if ( $f[2] === 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[2] ); ?></span>
					<?php endif; ?>
				</td>
			</tr>
			<?php endforeach; ?>
			</tbody>
		</table>
	</div>
	<?php if ( ! $is_active ) : ?>
	<div style="padding:14px 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 style="font-size:12px;color:var(--gt-subtle,#64748b);margin-top:10px;display:flex;align-items:center;justify-content:center;gap:6px;"><span style="color:#22c55e;">&#10003;</span>&nbsp;<?php esc_html_e( '30-day money-back guarantee. No questions asked.', 'gt-bogo-engine' ); ?></div>
	</div>
	<?php endif; ?>
</div>

<!-- ═══ LICENSE HISTORY ══════════════════════════════════════════════════════ -->
<?php if ( ! empty( $lic_history ) ) : ?>
<div class="gt-card gt-animate-in">
	<div class="gt-card-header"><h2 class="gt-card-title">📋 License History</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)">
				<?php foreach ( array( 'Time (UTC)', 'Action', 'Detail' ) as $c ) : ?>
				<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( $c ); ?></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"><?php echo esc_html( mb_strimwidth( $lh['message'] ?? '', 0, 100, '…' ) ); ?></td>
			</tr>
			<?php endforeach; ?>
			</tbody>
		</table>
	</div>
</div>
<?php endif; ?>

<script>
(function(){
var keyInput = document.getElementById('gt-lic-key');
var resultEl = document.getElementById('gt-lic-result');
var masked   = false;

window.gtLicToggleReveal = function() {
	if (!keyInput) return;
	masked = !masked;
	keyInput.type = masked ? 'password' : 'text';
};
window.gtLicCopyKey = function() {
	if (!keyInput) return;
	navigator.clipboard.writeText(keyInput.value).then(function(){ gtLicMsg('info','✓ Key copied.'); }).catch(function(){ keyInput.select(); document.execCommand('copy'); gtLicMsg('info','✓ Key selected.'); });
};
function doFetch(action, nonce, extra) {
	var fd = new FormData(); fd.append('action',action); fd.append('nonce',nonce);
	if (extra) Object.entries(extra).forEach(function(e){ fd.append(e[0],e[1]); });
	return fetch(ajaxurl,{method:'POST',body:fd}).then(function(r){return r.json();});
}
window.gtLicActivate = function(nonce) {
	var key = keyInput?.value.trim(); if (!key) { gtLicMsg('error','Enter a license key.'); return; }
	var btn = document.querySelector('.gt-btn-primary'); if (btn){btn.textContent='Activating…';btn.disabled=true;}
	doFetch('gtbogo_license_activate', nonce, {license_key:key}).then(function(resp){
		if (btn){btn.textContent='⚡ Activate';btn.disabled=false;}
		gtLicMsg(resp.success?'success':'error', resp.data?.message||resp.data||'Failed');
		if (resp.success) setTimeout(function(){location.reload();},1600);
	}).catch(function(){ if(btn){btn.textContent='⚡ Activate';btn.disabled=false;} gtLicMsg('error','Network error.'); });
};
window.gtLicDeactivate = function(nonce) {
	if (!confirm('Deactivate your license on this domain?')) return;
	doFetch('gtbogo_license_deactivate', nonce).then(function(resp){
		gtLicMsg(resp.success?'success':'error', resp.data||'Failed');
		if (resp.success) setTimeout(function(){location.reload();},1600);
	});
};
window.gtLicTest = function(nonce) {
	var btn=document.getElementById('gt-lic-test-btn'); if(btn){btn.textContent='Testing…';btn.disabled=true;}
	var start=Date.now();
	doFetch('gtbogo_license_test_connection',nonce).then(function(resp){
		var ms=Date.now()-start;
		if(btn){btn.textContent='🔌 Test';btn.disabled=false;}
		var lat=document.getElementById('gt-lic-latency'); if(lat) lat.textContent='('+ms+'ms)';
		gtLicMsg(resp.success?'success':'error', (resp.success?'✓ Server reachable — ':'✗ ')+(resp.data?.message||resp.data||'')+' '+ms+'ms');
	}).catch(function(){ if(btn){btn.textContent='🔌 Test';btn.disabled=false;} gtLicMsg('error','Network error.'); });
};
function gtLicMsg(type,msg) {
	if (!resultEl) return;
	var cols={success:['rgba(34,197,94,0.07)','rgba(34,197,94,0.05)','#86efac'],error:['rgba(239,68,68,0.07)','rgba(239,68,68,0.25)','#fca5a5'],info:['rgba(59,130,246,0.07)','rgba(59,130,246,0.25)','#93c5fd']};
	var c=cols[type]||cols.info;
	resultEl.style.cssText='display:block;padding:10px 14px;border-radius:7px;font-size:12px;margin-bottom:12px;background:'+c[0]+';border:1px solid '+c[1]+';color:'+c[2];
	resultEl.textContent=msg;
	clearTimeout(gtLicMsg._t);
	if (type!=='error') gtLicMsg._t=setTimeout(function(){resultEl.style.display='none';},5000);
}
})();
</script>

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