<?php
/**
 * System Health Tab — CapiFlow.
 *
 * Shows: PHP version, extensions, token status, queue stats, Event Match Quality.
 *
 * @package CapiFlow
 */

defined( 'ABSPATH' ) || exit;

// ── Build health checks ───────────────────────────────────────────────────────
use CapiFlow\Core\DB_Manager;
use CapiFlow\Core\Dataset_Quality;
use CapiFlow\Core\Encryption;

$capiflow_checks = array();

// 1. PHP Version
$capiflow_php_ok = version_compare( PHP_VERSION, '7.4', '>=' );
$capiflow_checks[] = array(
	'label'   => 'PHP Version',
	'status'  => $capiflow_php_ok ? 'good' : 'bad',
	'value'   => PHP_VERSION,
	'message' => $capiflow_php_ok ? '' : '7.4+ required',
);

// 2. OpenSSL extension
$capiflow_ssl_ok = extension_loaded( 'openssl' );
$capiflow_checks[] = array(
	'label'   => 'OpenSSL Extension',
	'status'  => $capiflow_ssl_ok ? 'good' : 'bad',
	'value'   => $capiflow_ssl_ok ? 'Loaded' : 'Missing',
	'message' => $capiflow_ssl_ok ? '' : 'Required for token encryption',
);

// 3. Action Scheduler
$capiflow_as_ok = function_exists( 'as_enqueue_async_action' );
$capiflow_checks[] = array(
	'label'   => 'Action Scheduler',
	'status'  => $capiflow_as_ok ? 'good' : 'bad',
	'value'   => $capiflow_as_ok ? 'Available' : 'Missing',
	'message' => $capiflow_as_ok ? '' : 'WooCommerce must be active',
);

// 4. Pixel ID configured
$capiflow_pixel_id = get_option( 'capiflow_pixel_id', '' );
$capiflow_checks[] = array(
	'label'   => 'Pixel ID',
	'status'  => ! empty( $capiflow_pixel_id ) ? 'good' : 'warning',
	'value'   => ! empty( $capiflow_pixel_id ) ? $capiflow_pixel_id : 'Not configured',
	'message' => empty( $capiflow_pixel_id ) ? 'Go to Settings → General to configure' : '',
);

// 5. Access Token
$capiflow_token_enc = get_option( 'capiflow_access_token', '' );
$capiflow_token_ok  = ! empty( $capiflow_token_enc );
$capiflow_checks[] = array(
	'label'   => 'Access Token',
	'status'  => $capiflow_token_ok ? 'good' : 'warning',
	'value'   => $capiflow_token_ok ? '••••••••••••••••' : 'Not configured',
	'message' => $capiflow_token_ok ? 'Stored AES-256 encrypted' : 'Go to Settings → General to configure',
);

// 6. Environment Mode + Test Event Code
$capiflow_env_mode  = get_option( 'capiflow_environment_mode', 'production' );
$capiflow_test_code = get_option( 'capiflow_test_event_code', '' );

if ( 'production' === $capiflow_env_mode ) {
	$capiflow_checks[] = array(
		'label'   => 'Environment Mode',
		'status'  => 'good',
		'value'   => '🟢 Production (Live)',
		'message' => 'Events count in ads & reporting',
	);
} elseif ( ! empty( $capiflow_test_code ) ) {
	$capiflow_checks[] = array(
		'label'   => 'Environment Mode',
		'status'  => 'warning',
		'value'   => '🟡 Test Mode (' . $capiflow_test_code . ')',
		'message' => '⚠ Events will NOT count in ads — switch to Production when done',
	);
} else {
	$capiflow_checks[] = array(
		'label'   => 'Environment Mode',
		'status'  => 'bad',
		'value'   => '🟡 Test Mode (no code set!)',
		'message' => 'Enter Test Event Code from Meta Events Manager or switch to Production',
	);
}

// 7. HPOS compatibility
$capiflow_hpos_active = false;
if ( function_exists( 'wc_get_container' ) ) {
	try {
		$capiflow_hpos_active = wc_get_container()
			->get( \Automattic\WooCommerce\Internal\DataStores\Orders\CustomOrdersTableController::class )
			->custom_orders_table_usage_is_enabled();
	} catch ( \Exception $capiflow_e ) {
		$capiflow_hpos_active = false;
	}
}
$capiflow_checks[] = array(
	'label'   => 'HPOS (Custom Order Tables)',
	'status'  => 'good',
	'value'   => $capiflow_hpos_active ? 'Active' : 'Legacy CPT mode',
	'message' => 'CapiFlow is compatible with both',
);

// 8. Data table
global $wpdb;
$capiflow_events_table = DB_Manager::events_table();
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
$capiflow_table_ok     = $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $capiflow_events_table ) ) === $capiflow_events_table;
$capiflow_checks[] = array(
	'label'   => 'Events Queue Table',
	'status'  => $capiflow_table_ok ? 'good' : 'bad',
	'value'   => $capiflow_table_ok ? $capiflow_events_table : 'Missing',
	'message' => $capiflow_table_ok ? '' : 'Deactivate & reactivate plugin to re-create',
);

// 9. Queue health
$capiflow_stats  = DB_Manager::get_queue_stats();
$capiflow_failed = (int) ( $capiflow_stats['failed'] ?? 0 );
$capiflow_checks[] = array(
	'label'   => 'Failed Events',
	'status'  => $capiflow_failed === 0 ? 'good' : ( $capiflow_failed <= 5 ? 'warning' : 'bad' ),
	'value'   => (string) $capiflow_failed,
	'message' => $capiflow_failed > 0 ? 'Check debug console for details' : '',
);

// 10. Event Match Quality (cached — no live API call)
$capiflow_emq = Dataset_Quality::get_overall_score();
$capiflow_checks[] = array(
	'label'   => 'Event Match Quality (EMQ)',
	'status'  => null !== $capiflow_emq ? ( $capiflow_emq >= 7 ? 'good' : ( $capiflow_emq >= 5 ? 'warning' : 'bad' ) ) : 'warning',
	'value'   => null !== $capiflow_emq ? (string) $capiflow_emq . '/10' : 'Not fetched yet',
	'message' => null === $capiflow_emq ? 'Requires CapiFlow Pro for live EMQ data' : '',
);

// Allow Pro plugin to add checks.
$capiflow_checks = apply_filters( 'capiflow_system_health_checks', $capiflow_checks );

$capiflow_icons = array( 'good' => '✅', 'warning' => '⚠', 'bad' => '❌' );
?>

<div class="capiflow-system-health">
	<h2><?php esc_html_e( '🏥 System Health', 'capiflow' ); ?></h2>
	<p style="color:#6b7280;font-size:13px;margin-top:-4px;">
		<?php esc_html_e( 'Real-time status of all CapiFlow components.', 'capiflow' ); ?>
	</p>

	<table class="widefat striped" style="max-width:900px;">
		<thead>
			<tr>
				<th><?php esc_html_e( 'Component', 'capiflow' ); ?></th>
				<th style="width:60px;"><?php esc_html_e( 'Status', 'capiflow' ); ?></th>
				<th><?php esc_html_e( 'Value', 'capiflow' ); ?></th>
				<th><?php esc_html_e( 'Notes', 'capiflow' ); ?></th>
			</tr>
		</thead>
		<tbody>
			<?php foreach ( $capiflow_checks as $capiflow_check ) : ?>
			<tr>
				<td><strong><?php echo esc_html( $capiflow_check['label'] ); ?></strong></td>
				<td style="text-align:center;font-size:16px;"><?php echo esc_html( $capiflow_icons[ $capiflow_check['status'] ] ?? '❓' ); ?></td>
				<td><code><?php echo esc_html( $capiflow_check['value'] ); ?></code></td>
				<td style="color:#6b7280;font-size:12px;"><?php echo esc_html( $capiflow_check['message'] ); ?></td>
			</tr>
			<?php endforeach; ?>
		</tbody>
	</table>

	<hr style="margin:24px 0;">

	<h3><?php esc_html_e( '📊 Queue Statistics', 'capiflow' ); ?></h3>
	<div style="display:flex;gap:12px;flex-wrap:wrap;max-width:600px;">
		<?php
		$capiflow_stat_items = array(
			'pending'    => array( '⏳', __( 'Pending', 'capiflow' ), '#f59e0b' ),
			'processing' => array( '⚙', __( 'Processing', 'capiflow' ), '#2563eb' ),
			'sent'       => array( '✅', __( 'Sent', 'capiflow' ), '#16a34a' ),
			'failed'     => array( '❌', __( 'Failed', 'capiflow' ), '#dc2626' ),
		);
		foreach ( $capiflow_stat_items as $capiflow_key => $capiflow_info ) :
		?>
		<div style="background:#fff;border:1px solid #e5e7eb;border-radius:8px;padding:16px 20px;min-width:100px;text-align:center;">
			<div style="font-size:20px;"><?php echo esc_html( $capiflow_info[0] ); ?></div>
			<div style="font-size:24px;font-weight:800;color:<?php echo esc_attr( $capiflow_info[2] ); ?>;">
				<?php echo esc_html( $capiflow_stats[ $capiflow_key ] ?? 0 ); ?>
			</div>
			<div style="font-size:11px;color:#6b7280;"><?php echo esc_html( $capiflow_info[1] ); ?></div>
		</div>
		<?php endforeach; ?>
	</div>

	<hr style="margin:24px 0;">

	<h3><?php esc_html_e( '🔧 Integrations', 'capiflow' ); ?></h3>
	<table class="widefat" style="max-width:500px;">
		<tr>
			<td>✅ Meta Conversions API (CAPI)</td>
			<td><span style="color:#16a34a;font-weight:600;">Active</span></td>
		</tr>
		<tr>
			<td>🔒 GA4 Measurement Protocol</td>
			<td><?php echo \CapiFlow\Core\License_Manager::is_pro_active()
				? '<span style="color:#16a34a;font-weight:600;">' . esc_html__( 'Pro Active', 'capiflow' ) . '</span>'
				: '<span class="capiflow-pro-badge">PRO</span>'; ?></td>
		</tr>
		<tr>
			<td>🔒 Google Ads Enhanced Conversions</td>
			<td><?php echo \CapiFlow\Core\License_Manager::is_pro_active()
				? '<span style="color:#16a34a;font-weight:600;">' . esc_html__( 'Pro Active', 'capiflow' ) . '</span>'
				: '<span class="capiflow-pro-badge">PRO</span>'; ?></td>
		</tr>
		<tr>
			<td>🔒 TikTok Events API</td>
			<td><?php echo \CapiFlow\Core\License_Manager::is_pro_active()
				? '<span style="color:#16a34a;font-weight:600;">' . esc_html__( 'Pro Active', 'capiflow' ) . '</span>'
				: '<span class="capiflow-pro-badge">PRO</span>'; ?></td>
		</tr>
	</table>

	<hr style="margin:24px 0;">

	<h3><?php esc_html_e( '📡 Meta Integration Quality', 'capiflow' ); ?></h3>
	<p style="color:#6b7280;font-size:12px;margin-top:-8px;">
		<?php esc_html_e( 'Event Match Quality fetched daily via Action Scheduler.', 'capiflow' ); ?>
	</p>
	<?php
	$capiflow_quality = method_exists( Dataset_Quality::class, 'get_cached' ) ? Dataset_Quality::get_cached() : null;
	if ( $capiflow_quality && ! empty( $capiflow_quality['web'] ) ) :
	?>
	<table class="widefat striped" style="max-width:900px;margin-bottom:16px;">
		<thead>
			<tr>
				<th><?php esc_html_e( 'Event', 'capiflow' ); ?></th>
				<th><?php esc_html_e( 'EMQ Score', 'capiflow' ); ?></th>
				<th><?php esc_html_e( 'Match Keys', 'capiflow' ); ?></th>
				<th><?php esc_html_e( 'Freshness', 'capiflow' ); ?></th>
				<th><?php esc_html_e( 'Dedup %', 'capiflow' ); ?></th>
			</tr>
		</thead>
		<tbody>
		<?php foreach ( $capiflow_quality['web'] as $capiflow_ev ) :
			$capiflow_emq_score  = $capiflow_ev['event_match_quality']['composite_score'] ?? null;
			$capiflow_keys       = $capiflow_ev['event_match_quality']['match_key_feedback'] ?? [];
			$capiflow_key_total  = count( $capiflow_keys );
			$capiflow_key_hit    = count( array_filter( $capiflow_keys, fn( $capiflow_k ) => ( $capiflow_k['coverage']['percentage'] ?? 0 ) > 0 ) );
			$capiflow_freshness  = $capiflow_ev['data_freshness']['upload_frequency'] ?? '—';
			$capiflow_dedup_info = $capiflow_ev['dedupe_key_feedback'] ?? [];
			$capiflow_dedup_pct  = ! empty( $capiflow_dedup_info ) ? ( $capiflow_dedup_info[0]['server_events_with_dedupe_key']['percentage'] ?? null ) : null;
			$capiflow_emq_color  = null !== $capiflow_emq_score ? ( $capiflow_emq_score >= 7 ? '#16a34a' : ( $capiflow_emq_score >= 5 ? '#f59e0b' : '#dc2626' ) ) : '#9ca3af';
		?>
		<tr>
			<td><strong><?php echo esc_html( $capiflow_ev['event_name'] ); ?></strong></td>
			<td><span style="color:<?php echo esc_attr( $capiflow_emq_color ); ?>;font-weight:700;"><?php echo null !== $capiflow_emq_score ? esc_html( $capiflow_emq_score . '/10' ) : '—'; ?></span></td>
			<td><?php echo esc_html( $capiflow_key_total > 0 ? "$capiflow_key_hit/$capiflow_key_total" : '—' ); ?></td>
			<td><?php echo esc_html( $capiflow_freshness ); ?></td>
			<td><?php echo null !== $capiflow_dedup_pct ? esc_html( round( $capiflow_dedup_pct ) . '%' ) : '—'; ?></td>
		</tr>
		<?php endforeach; ?>
		</tbody>
	</table>
	<?php
	$capiflow_diags = Dataset_Quality::get_diagnostics();
	if ( ! empty( $capiflow_diags ) ) :
	?>
	<div style="background:#fff1f2;border:1px solid #fca5a5;border-radius:8px;padding:14px;max-width:900px;">
		<strong style="color:#991b1b;">⚠️ <?php echo esc_html( count( $capiflow_diags ) . ' ' . __( 'Diagnostics', 'capiflow' ) ); ?></strong>
		<ul style="margin:8px 0 0;padding-left:18px;font-size:12px;color:#7f1d1d;">
		<?php foreach ( $capiflow_diags as $capiflow_d ) : ?>
			<li><?php echo esc_html( $capiflow_d['event_name'] . ': ' . ( $capiflow_d['name'] ?? '' ) . ' — ' . ( $capiflow_d['description'] ?? '' ) ); ?></li>
		<?php endforeach; ?>
		</ul>
	</div>
	<?php
	endif;
	else :
	?>
	<p style="color:#9ca3af;font-size:13px;">
		<?php esc_html_e( 'EMQ data available ~24h after your first event. Fetched automatically via nightly cron.', 'capiflow' ); ?>
	</p>
	<?php endif; ?>

</div>
