<?php
// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals
// phpcs:disable WordPress.Security.NonceVerification
// phpcs:disable WordPress.DB.PreparedSQL
// phpcs:disable WordPress.DB.DirectDatabaseQuery
// phpcs:disable PluginCheck.CodeAnalysis
// phpcs:disable WordPressVIPMinimum
/**
 * GT BOGO Engine — Store Health Monitor Admin Page
 *
 * @package GT_BOGO_Engine
 * @since   3.23.3
 */


if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
if ( ! current_user_can( 'manage_options' ) ) {
	return;
}

// Get or trigger scan
$force   = isset( $_GET['rescan'] ) && $_GET['rescan'] === '1'; // phpcs:ignore
$results = class_exists( 'GT_BOGO_Store_Health_Monitor' )
	? GT_BOGO_Store_Health_Monitor::get_results( $force )
	: array();
$history = class_exists( 'GT_BOGO_Store_Health_Monitor' )
	? GT_BOGO_Store_Health_Monitor::get_history()
	: array();

$checks    = $results['checks'] ?? array();
$score     = $results['score'] ?? 0;
$criticals = $results['criticals'] ?? 0;
$warnings  = $results['warnings'] ?? 0;
$scanned   = $results['scanned_at'] ?? 'Never';
$nonce     = wp_create_nonce( 'gtbogo_health_nonce' );

// Score color
$score_color = $score >= 80 ? '#22c55e' : ( $score >= 50 ? '#f59e0b' : '#E10000' );
$score_label = $score >= 80 ? 'Healthy' : ( $score >= 50 ? 'Needs Attention' : 'Critical Issues' );

// Group checks by severity
$crit_checks = array_filter( $checks, fn( $c ) => $c['severity'] === 'critical' );
$warn_checks = array_filter( $checks, fn( $c ) => $c['severity'] === 'warning' );
$info_checks = array_filter( $checks, fn( $c ) => $c['severity'] === 'info' );

require_once __DIR__ . '/../ui-system/wrapper-start.php';
if ( ! function_exists( 'gt_bogo_has_pro' ) || ! gt_bogo_has_pro() ) {
	gtbogo_upgrade_card( 'Store Health Monitor', 'Automated health checks across 15 critical performance and configuration categories.' );
	require_once __DIR__ . '/../ui-system/wrapper-end.php';
	return;
}
?>

<div class="gt-page-header gt-animate-in">
	<div>
		<h1 class="gt-page-title">🏥 Store Health Monitor</h1>
		<p class="gt-page-subtitle">Real-time performance, security, and optimization intelligence — with one-click fixes</p>
	</div>
	<div style="display:flex;align-items:center;gap:12px">
		<span style="color:var(--gt-soft);font-size:11px">Last scan: <?php echo esc_html( $scanned ); ?> UTC</span>
		<button id="gtbogo-rescan-btn" class="gt-btn gt-btn-secondary" data-nonce="<?php echo esc_attr( $nonce ); ?>">
			↺ Re-scan Now
		</button>
		<span class="gt-badge <?php echo $criticals > 0 ? 'gt-badge-warn' : 'gt-badge-active'; ?>">
			<?php echo $criticals > 0 ? esc_html( "⚠ {$criticals} Critical" ) : '✓ No Critical Issues'; ?>
		</span>
	</div>
</div>

<!-- Health Score + KPIs -->
<div class="gt-metrics gt-animate-in" style="margin-bottom:24px">
	<div class="gt-metric" style="--gt-metric-c:<?php echo esc_attr( $score_color ); ?>">
		<span class="gt-metric-icon">🎯</span>
		<div class="gt-metric-label">Health Score</div>
		<div class="gt-metric-value" style="font-size:2.2rem;font-weight:900;color:<?php echo esc_attr( $score_color ); ?>"><?php echo (int) $score; ?></div>
		<div class="gt-metric-label" style="color:<?php echo esc_attr( $score_color ); ?>;font-weight:700"><?php echo esc_html( $score_label ); ?></div>
	</div>
	<div class="gt-metric" style="--gt-metric-c:#E10000">
		<span class="gt-metric-icon">🚨</span>
		<div class="gt-metric-label">Critical Issues</div>
		<div class="gt-metric-value" style="color:#E10000"><?php echo (int) $criticals; ?></div>
	</div>
	<div class="gt-metric" style="--gt-metric-c:#f59e0b">
		<span class="gt-metric-icon">⚠</span>
		<div class="gt-metric-label">Warnings</div>
		<div class="gt-metric-value" style="color:#f59e0b"><?php echo (int) $warnings; ?></div>
	</div>
	<div class="gt-metric" style="--gt-metric-c:#3b82f6">
		<span class="gt-metric-icon">📊</span>
		<div class="gt-metric-label">Checks Run</div>
		<div class="gt-metric-value"><?php echo count( $checks ); ?></div>
	</div>
</div>

<!-- Score Bar -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px;padding:20px 24px">
	<div style="display:flex;justify-content:space-between;margin-bottom:8px">
		<span style="color:var(--gt-soft);font-size:12px;font-weight:600;letter-spacing:0.05em">STORE HEALTH</span>
		<span style="color:<?php echo esc_attr( $score_color ); ?>;font-weight:700;font-size:14px"><?php echo (int) $score; ?>/100 — <?php echo esc_html( $score_label ); ?></span>
	</div>
	<div style="height:8px;background:rgba(255,255,255,0.08);border-radius:4px;overflow:hidden">
		<div style="height:100%;width:<?php echo (int) $score; ?>%;background:<?php echo esc_attr( $score_color ); ?>;border-radius:4px;transition:width 1s ease"></div>
	</div>
</div>

<!-- 7-Day History -->
<?php if ( ! empty( $history ) ) : ?>
<div class="gt-card gt-animate-in" style="margin-bottom:20px;padding:20px 24px">
	<div style="color:var(--gt-soft);font-size:12px;font-weight:600;letter-spacing:0.05em;margin-bottom:16px">7-DAY HEALTH TREND</div>
	<div style="display:flex;align-items:flex-end;gap:8px;height:60px">
		<?php
		foreach ( array_slice( $history, -7, 7, true ) as $date => $day ) :
			$h  = max( 10, round( $day['score'] / 100 * 60 ) );
			$hc = $day['score'] >= 80 ? '#22c55e' : ( $day['score'] >= 50 ? '#f59e0b' : '#E10000' );
			$dn = gmdate( 'D', strtotime( $date ) );
			?>
		<div style="flex:1;display:flex;flex-direction:column;align-items:center;gap:4px">
			<div style="font-size:10px;color:<?php echo esc_attr( $hc ); ?>;font-weight:700"><?php echo (int) $day['score']; ?></div>
			<div style="width:100%;height:<?php echo (int) $h; ?>px;background:<?php echo esc_attr( $hc ); ?>;border-radius:3px 3px 0 0;opacity:0.85"></div>
			<div style="font-size:10px;color:var(--gt-soft)"><?php echo esc_html( $dn ); ?></div>
		</div>
		<?php endforeach; ?>
	</div>
</div>
<?php endif; ?>

<!-- CRITICAL Checks -->
<?php if ( ! empty( $crit_checks ) ) : ?>
<div class="gt-card gt-animate-in" style="margin-bottom:20px;border:1px solid rgba(225,0,0,0.3)">
	<div style="padding:16px 20px;border-bottom:1px solid rgba(255,255,255,0.06);display:flex;align-items:center;gap:8px">
		<span style="color:#E10000;font-size:16px">🚨</span>
		<span style="font-weight:700;color:var(--gt-white);font-size:14px">Critical Issues</span>
		<span style="margin-left:auto;background:#E10000;color:#fff;border-radius:20px;padding:2px 10px;font-size:11px;font-weight:700"><?php echo count( $crit_checks ); ?></span>
	</div>
	<?php foreach ( $crit_checks as $check ) : ?>
	<div class="gtbogo-check-row" data-id="<?php echo esc_attr( $check['id'] ); ?>"
		style="padding:16px 20px;border-bottom:1px solid rgba(255,255,255,0.04);display:flex;align-items:flex-start;gap:16px">
		<div style="flex-shrink:0;width:28px;height:28px;border-radius:50%;background:<?php echo $check['status'] === 'ok' ? 'rgba(34,197,94,0.15)' : 'rgba(225,0,0,0.15)'; ?>;display:flex;align-items:center;justify-content:center;font-size:14px">
			<?php echo $check['status'] === 'ok' ? '✓' : '✗'; ?>
		</div>
		<div style="flex:1;min-width:0">
			<div style="font-weight:700;color:var(--gt-white);margin-bottom:4px;display:flex;align-items:center;gap:8px">
				<?php echo esc_html( $check['title'] ); ?>
				<span style="font-size:10px;font-weight:600;padding:2px 8px;border-radius:20px;background:<?php echo $check['status'] === 'ok' ? 'rgba(34,197,94,0.15)' : 'rgba(225,0,0,0.15)'; ?>;color:<?php echo $check['status'] === 'ok' ? '#22c55e' : '#E10000'; ?>">
					<?php echo $check['status'] === 'ok' ? 'OK' : esc_html( strtoupper( $check['severity'] ) ); ?>
				</span>
				<span style="font-size:10px;color:var(--gt-soft);font-weight:400">Current: <strong style="color:var(--gt-white)"><?php echo esc_html( $check['current'] ); ?></strong></span>
			</div>
			<div style="font-size:12px;color:var(--gt-soft);line-height:1.6"><?php echo esc_html( $check['message'] ); ?></div>
		</div>
		<?php if ( ! empty( $check['fix_id'] ) && $check['status'] !== 'ok' ) : ?>
		<button class="gtbogo-fix-btn gt-btn" style="flex-shrink:0;background:#E10000;color:#fff;border:none;padding:8px 16px;font-size:12px;font-weight:700;cursor:pointer;border-radius:6px"
			data-fix="<?php echo esc_attr( $check['fix_id'] ); ?>"
			data-nonce="<?php echo esc_attr( $nonce ); ?>"
			data-check="<?php echo esc_attr( $check['id'] ); ?>">
			<?php echo esc_html( $check['fix_label'] ); ?>
		</button>
		<?php endif; ?>
	</div>
	<?php endforeach; ?>
</div>
<?php endif; ?>

<!-- WARNING Checks -->
<?php if ( ! empty( $warn_checks ) ) : ?>
<div class="gt-card gt-animate-in" style="margin-bottom:20px;border:1px solid rgba(245,158,11,0.2)">
	<div style="padding:16px 20px;border-bottom:1px solid rgba(255,255,255,0.06);display:flex;align-items:center;gap:8px">
		<span style="font-size:16px">⚠</span>
		<span style="font-weight:700;color:var(--gt-white);font-size:14px">Warnings</span>
		<span style="margin-left:auto;background:rgba(245,158,11,0.2);color:#f59e0b;border-radius:20px;padding:2px 10px;font-size:11px;font-weight:700"><?php echo count( $warn_checks ); ?></span>
	</div>
	<?php foreach ( $warn_checks as $check ) : ?>
	<div class="gtbogo-check-row" data-id="<?php echo esc_attr( $check['id'] ); ?>"
		style="padding:16px 20px;border-bottom:1px solid rgba(255,255,255,0.04);display:flex;align-items:flex-start;gap:16px">
		<div style="flex-shrink:0;width:28px;height:28px;border-radius:50%;background:<?php echo $check['status'] === 'ok' ? 'rgba(34,197,94,0.15)' : 'rgba(245,158,11,0.15)'; ?>;display:flex;align-items:center;justify-content:center;font-size:14px">
			<?php echo $check['status'] === 'ok' ? '✓' : '⚠'; ?>
		</div>
		<div style="flex:1;min-width:0">
			<div style="font-weight:700;color:var(--gt-white);margin-bottom:4px;display:flex;align-items:center;gap:8px;flex-wrap:wrap">
				<?php echo esc_html( $check['title'] ); ?>
				<span style="font-size:10px;font-weight:600;padding:2px 8px;border-radius:20px;background:<?php echo $check['status'] === 'ok' ? 'rgba(34,197,94,0.15)' : 'rgba(245,158,11,0.15)'; ?>;color:<?php echo $check['status'] === 'ok' ? '#22c55e' : '#f59e0b'; ?>">
					<?php echo $check['status'] === 'ok' ? 'OK' : 'WARNING'; ?>
				</span>
				<span style="font-size:10px;color:var(--gt-soft);font-weight:400">Current: <strong style="color:var(--gt-white)"><?php echo esc_html( $check['current'] ); ?></strong></span>
			</div>
			<div style="font-size:12px;color:var(--gt-soft);line-height:1.6"><?php echo esc_html( $check['message'] ); ?></div>
		</div>
		<?php if ( ! empty( $check['fix_id'] ) && $check['status'] !== 'ok' ) : ?>
		<button class="gtbogo-fix-btn gt-btn" style="flex-shrink:0;background:rgba(245,158,11,0.15);color:#f59e0b;border:1px solid rgba(245,158,11,0.3);padding:8px 16px;font-size:12px;font-weight:700;cursor:pointer;border-radius:6px"
			data-fix="<?php echo esc_attr( $check['fix_id'] ); ?>"
			data-nonce="<?php echo esc_attr( $nonce ); ?>"
			data-check="<?php echo esc_attr( $check['id'] ); ?>">
			<?php echo esc_html( $check['fix_label'] ); ?>
		</button>
		<?php endif; ?>
	</div>
	<?php endforeach; ?>
</div>
<?php endif; ?>

<!-- INFO Checks -->
<?php if ( ! empty( $info_checks ) ) : ?>
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
	<div style="padding:16px 20px;border-bottom:1px solid rgba(255,255,255,0.06);display:flex;align-items:center;gap:8px">
		<span style="font-size:16px">ℹ</span>
		<span style="font-weight:700;color:var(--gt-white);font-size:14px">Store Insights</span>
	</div>
	<?php foreach ( $info_checks as $check ) : ?>
	<div class="gtbogo-check-row" data-id="<?php echo esc_attr( $check['id'] ); ?>"
		style="padding:14px 20px;border-bottom:1px solid rgba(255,255,255,0.04);display:flex;align-items:flex-start;gap:16px">
		<div style="flex-shrink:0;width:28px;height:28px;border-radius:50%;background:<?php echo $check['status'] === 'ok' ? 'rgba(34,197,94,0.1)' : 'rgba(59,130,246,0.1)'; ?>;display:flex;align-items:center;justify-content:center;font-size:12px">
			<?php echo $check['status'] === 'ok' ? '✓' : 'ℹ'; ?>
		</div>
		<div style="flex:1;min-width:0">
			<div style="font-weight:600;color:var(--gt-white);margin-bottom:3px;display:flex;align-items:center;gap:8px;flex-wrap:wrap;font-size:13px">
				<?php echo esc_html( $check['title'] ); ?>
				<span style="font-size:10px;color:var(--gt-soft);font-weight:400"><?php echo esc_html( $check['current'] ); ?></span>
			</div>
			<div style="font-size:12px;color:var(--gt-soft);line-height:1.5"><?php echo esc_html( $check['message'] ); ?></div>
		</div>
		<?php if ( ! empty( $check['fix_id'] ) && $check['status'] !== 'ok' ) : ?>
		<button class="gtbogo-fix-btn gt-btn gt-btn-secondary" style="flex-shrink:0;font-size:12px;padding:6px 14px;cursor:pointer"
			data-fix="<?php echo esc_attr( $check['fix_id'] ); ?>"
			data-nonce="<?php echo esc_attr( $nonce ); ?>"
			data-check="<?php echo esc_attr( $check['id'] ); ?>">
			<?php echo esc_html( $check['fix_label'] ); ?>
		</button>
		<?php endif; ?>
	</div>
	<?php endforeach; ?>
</div>
<?php endif; ?>

<!-- Inline JS -->
<script>
(function(){
	var ajaxurl = '<?php echo esc_js( admin_url( 'admin-ajax.php' ) ); ?>';

	// Fix buttons
	document.querySelectorAll('.gtbogo-fix-btn').forEach(function(btn){
		btn.addEventListener('click', function(){
			var origText = btn.textContent;
			btn.disabled = true;
			btn.textContent = 'Applying fix...';
			fetch(ajaxurl, {
				method: 'POST',
				headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
				body: 'action=gtbogo_health_fix'
					+ '&fix_id=' + encodeURIComponent(btn.dataset.fix)
					+ '&nonce='  + encodeURIComponent(btn.dataset.nonce)
			})
			.then(function(r){ return r.json(); })
			.then(function(d){
				if ( d.success && d.data && d.data.fix && d.data.fix.success ) {
					var row = btn.closest('.gtbogo-check-row');
					if ( row ) {
						row.style.opacity = '0.5';
						btn.textContent = '✓ Fixed';
						btn.style.background = '#22c55e';
						btn.style.color = '#fff';
						btn.style.borderColor = '#22c55e';
					}
					// Show fix message
					var msg = document.createElement('div');
					msg.style.cssText = 'position:fixed;bottom:24px;right:24px;background:#0a1628;border:1px solid #22c55e;color:#22c55e;padding:14px 20px;border-radius:8px;font-size:13px;font-weight:600;z-index:9999;max-width:400px;box-shadow:0 8px 32px rgba(0,0,0,0.5)';
					msg.textContent = d.data.fix.message || 'Fix applied.';
					document.body.appendChild(msg);
					setTimeout(function(){ msg.remove(); }, 5000);
					setTimeout(function(){ location.reload(); }, 2000);
				} else {
					btn.textContent = 'Failed — try manually';
					btn.disabled = false;
					btn.style.opacity = '0.7';
				}
			})
			.catch(function(){
				btn.textContent = origText;
				btn.disabled = false;
			});
		});
	});

	// Re-scan button
	var rescanBtn = document.getElementById('gtbogo-rescan-btn');
	if ( rescanBtn ) {
		rescanBtn.addEventListener('click', function(){
			rescanBtn.disabled = true;
			rescanBtn.textContent = '↺ Scanning...';
			fetch(ajaxurl, {
				method: 'POST',
				headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
				body: 'action=gtbogo_health_rescan&nonce=' + encodeURIComponent(rescanBtn.dataset.nonce)
			})
			.then(function(r){ return r.json(); })
			.then(function(d){
				if ( d.success ) location.reload();
				else { rescanBtn.textContent = '↺ Re-scan Now'; rescanBtn.disabled = false; }
			})
			.catch(function(){
				rescanBtn.textContent = '↺ Re-scan Now';
				rescanBtn.disabled = false;
			});
		});
	}
})();
</script>

<!-- ═══════════ Stock Velocity (Velocity‑to‑Zero) ═══════════ -->
<div class="gt-card" style="margin-top:24px">
	<div class="gt-card-header">
		<h3 style="margin:0;font-size:16px;font-weight:700">📊 Inventory Velocity</h3>
		<span style="font-size:11px;color:var(--gt-soft)">Last scan: 
		<?php
			$sv_last = class_exists( 'GT_BOGO_Stock_Velocity' )
				? GT_BOGO_Stock_Velocity::instance()->get_last_scan_time()
				: 'N/A';
			echo esc_html( $sv_last );
		?>
		UTC</span>
	</div>
	<div class="gt-card-body" style="margin-top:12px">
		<table class="gt-table" style="width:100%">
			<thead>
				<tr>
					<th>Product ID</th>
					<th>Days to Zero</th>
					<th>Risk Level</th>
				</tr>
			</thead>
			<tbody>
				<?php
				$at_risk = class_exists( 'GT_BOGO_Stock_Velocity' )
					? GT_BOGO_Stock_Velocity::instance()->get_products_at_risk( 14 )
					: array();
				if ( empty( $at_risk ) ) :
					?>
					<tr><td colspan="3" style="text-align:center;color:var(--gt-soft)">No products at risk.</td></tr>
					<?php
				else :
					foreach ( $at_risk as $row ) :
						$days  = (float) ( $row['days_to_zero'] ?? 0 );
						$level = $days <= 7 ? '🔴 CRITICAL' : ( $days <= 14 ? '🟡 WARNING' : '🟢 WATCH' );
						$color = $days <= 7 ? '#ef4444' : ( $days <= 14 ? '#f59e0b' : '#22c55e' );
						?>
					<tr>
						<td><?php echo absint( $row['product_id'] ); ?></td>
						<td><?php echo esc_html( $days ); ?> days</td>
						<td style="color:<?php echo esc_attr( $color ); ?>;font-weight:700"><?php echo esc_html( $level ); ?></td>
					</tr>
						<?php
				endforeach;
endif;
				?>
			</tbody>
		</table>
		<div style="margin-top:12px;display:flex;gap:8px">
			<button id="gtbogo-sv-scan-btn" class="gt-btn gt-btn-secondary" style="font-size:11px">
				↻ Scan Inventory Velocity
			</button>
			<span id="gtbogo-sv-status" style="font-size:11px;color:var(--gt-soft);align-self:center"></span>
		</div>
		<script>
		document.getElementById('gtbogo-sv-scan-btn')?.addEventListener('click', function(){
			var btn = this;
			var status = document.getElementById('gtbogo-sv-status');
			btn.disabled = true;
			btn.textContent = 'Scanning…';
			status.textContent = 'Please wait — scanning all products.';
			fetch(ajaxurl, {
				method: 'POST',
				headers: {'Content-Type': 'application/x-www-form-urlencoded'},
				body: 'action=gt_bogo_stock_velocity_scan&nonce=<?php echo esc_js( wp_create_nonce( 'gtbogo_health_nonce' ) ); ?>'
			})
			.then(function(r){ return r.json(); })
			.then(function(d){
				if(d.success){
					status.textContent = 'Scan complete. Refreshing…';
					location.reload();
				} else {
					status.textContent = 'Scan failed: ' + (d.data?.message || 'Unknown error');
					btn.disabled = false;
					btn.textContent = '↻ Scan Inventory Velocity';
				}
			})
			.catch(function(){
				status.textContent = 'Network error.';
				btn.disabled = false;
				btn.textContent = '↻ Scan Inventory Velocity';
			});
		});
		</script>
	</div>
</div>

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