<?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 — Decision Provenance Log
 *
 * Full audit trail of every discount decision:
 *   - KPI cards: total, fired, blocked, fired %, blocked %
 *   - Live auto-refreshing feed (last 10 decisions)
 *   - AJAX filter bar: rule / status / gate / date range
 *   - Paginated decisions table (25/page, AJAX load)
 *   - Per-decision accordion: all 24 signal values as animated bars,
 *     PCV score, gate passed, discount %, outcome chain
 *   - Status & gate distribution charts (Chart.js)
 *   - CSV export of filtered decisions
 *   - Bulk purge controls with age selector
 *   - Decision replay button
 *
 * Data source: GT_BOGO_Decision_Provenance
 * Table: gtbogo_provenance (decision_id, customer_hash, rule_id,
 *        signal_state JSON, pcv_score, gate_passed, discount_pct,
 *        status, outcome, created_at)
 *
 * @package GT_BOGO_Engine
 * @since   5.0.0
 */
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
if ( ! current_user_can( 'manage_woocommerce' ) ) {
	wp_die( esc_html__( 'Insufficient permissions.', 'gt-bogo-engine' ) );
}

global $wpdb;
$nonce = wp_create_nonce( 'gtbogo_decision_log' );

/* ── Filters from GET ────────────────────────────────────────────────────── */
$f_rule   = sanitize_key( wp_unslash( $_GET['rule_id'] ?? '' ) );
$f_status = sanitize_key( wp_unslash( $_GET['status'] ?? '' ) );
$f_gate   = absint( $_GET['gate'] ?? 0 );
$f_from   = sanitize_text_field( wp_unslash( $_GET['date_from'] ?? '' ) );
$f_to     = sanitize_text_field( wp_unslash( $_GET['date_to'] ?? '' ) );
$f_search = sanitize_text_field( wp_unslash( $_GET['search'] ?? '' ) );
$paged    = max( 1, absint( $_GET['paged'] ?? 1 ) );
$per_page = 25;

/* ── Provenance instance ─────────────────────────────────────────────────── */
$prov = class_exists( 'GT_BOGO_Decision_Provenance' )
	? GT_BOGO_Decision_Provenance::instance()
	: null;

/* ── Has provenance table? ───────────────────────────────────────────────── */
$prov_tbl = $wpdb->prefix . 'gtbogo_provenance';
$has_prov = (bool) $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $prov_tbl ) ); // phpcs:ignore

/* ── Stats ───────────────────────────────────────────────────────────────── */
$stats = $prov && $has_prov ? $prov->get_stats( 30 ) : array(
	'total_decisions'  => 0,
	'recent_decisions' => 0,
	'fired_count'      => 0,
	'blocked_count'    => 0,
	'fired_pct'        => 0,
	'blocked_pct'      => 0,
);

/* ── Filtered decisions (paginated) ─────────────────────────────────────── */
$filters = array();
if ( $f_rule ) {
	$filters['rule_id'] = $f_rule;
}
if ( $f_status ) {
	$filters['status'] = $f_status;
}
if ( $f_gate ) {
	$filters['gate'] = $f_gate;
}
if ( $f_from ) {
	$filters['date_from'] = $f_from . ' 00:00:00';
}
if ( $f_to ) {
	$filters['date_to'] = $f_to . ' 23:59:59';
}

/* Direct paged query for offset support */
$decisions  = array();
$total_rows = 0;
if ( $has_prov ) {
	$where_parts = array( '1=1' );
	$where_vals  = array();

	if ( $f_rule ) {
		$where_parts[] = 'rule_id = %s';
		$where_vals[]  = $f_rule; }
	if ( $f_status ) {
		$where_parts[] = 'status = %s';
		$where_vals[]  = $f_status; }
	if ( $f_gate ) {
		$where_parts[] = 'gate_passed = %d';
		$where_vals[]  = $f_gate; }
	if ( $f_from ) {
		$where_parts[] = 'created_at >= %s';
		$where_vals[]  = $f_from . ' 00:00:00'; }
	if ( $f_to ) {
		$where_parts[] = 'created_at <= %s';
		$where_vals[]  = $f_to . ' 23:59:59'; }
	if ( $f_search ) {
		$where_parts[] = '(rule_id LIKE %s OR decision_id LIKE %s)';
		$where_vals[]  = '%' . $wpdb->esc_like( $f_search ) . '%';
		$where_vals[]  = '%' . $wpdb->esc_like( $f_search ) . '%'; }

	$where_sql = implode( ' AND ', $where_parts );
	$offset    = ( $paged - 1 ) * $per_page;

	$count_args = array_merge( $where_vals );
	$total_rows = $where_vals
        ? (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM {$prov_tbl} WHERE {$where_sql}", ...$count_args ) ) // phpcs:ignore
        : (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$prov_tbl}" ); // phpcs:ignore

	$row_args  = array_merge( $where_vals, array( $per_page, $offset ) );
	$decisions = $where_vals
        ? ( $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$prov_tbl} WHERE {$where_sql} ORDER BY created_at DESC LIMIT %d OFFSET %d", ...$row_args ), ARRAY_A ) ?: [] ) // phpcs:ignore
        : ( $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$prov_tbl} ORDER BY created_at DESC LIMIT %d OFFSET %d", $per_page, $offset ), ARRAY_A ) ?: [] ); // phpcs:ignore
}

$total_pages = $total_rows > 0 ? (int) ceil( $total_rows / $per_page ) : 1;

/* ── Live feed (last 10, no filters) ────────────────────────────────────── */
$live_feed = $has_prov
    ? ( $wpdb->get_results( $wpdb->prepare( "SELECT decision_id, rule_id, status, outcome, pcv_score, discount_pct, gate_passed, created_at FROM {$prov_tbl} ORDER BY created_at DESC LIMIT %d", 10 ), ARRAY_A ) ?: [] ) // phpcs:ignore
	: array();

/* ── Status distribution for chart ──────────────────────────────────────── */
$status_dist = array();
if ( $has_prov ) {
    $sd = $wpdb->get_results( // phpcs:ignore
		$wpdb->prepare( "SELECT status, COUNT(*) as cnt FROM {$prov_tbl} WHERE created_at >= DATE_SUB(UTC_TIMESTAMP(), INTERVAL 30 DAY) GROUP BY status ORDER BY cnt DESC", ),
		ARRAY_A
	) ?: array();
	foreach ( $sd as $row ) {
		$status_dist[ $row['status'] ] = (int) $row['cnt'];
	}
}

/* ── Gate distribution for chart ────────────────────────────────────────── */
$gate_dist = array();
if ( $has_prov ) {
    $gd = $wpdb->get_results( // phpcs:ignore
		$wpdb->prepare( "SELECT gate_passed, COUNT(*) as cnt FROM {$prov_tbl} WHERE created_at >= DATE_SUB(UTC_TIMESTAMP(), INTERVAL 30 DAY) GROUP BY gate_passed ORDER BY gate_passed", ),
		ARRAY_A
	) ?: array();
	foreach ( $gd as $row ) {
		$gate_dist[ (string) (int) $row['gate_passed'] ] = (int) $row['cnt'];
	}
}

/* ── All active rule IDs for filter dropdown ─────────────────────────────── */
$rules_tbl = $wpdb->prefix . 'gtbogo_rules';
$all_rules = array();
if ( $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $rules_tbl ) ) ) { // phpcs:ignore
    $all_rules = $wpdb->get_results( "SELECT id, name FROM {$rules_tbl} WHERE status='active' ORDER BY name LIMIT 100", ARRAY_A ) ?: []; // phpcs:ignore
}

/* ── Chart JSON ──────────────────────────────────────────────────────────── */
$status_colors       = array(
	'FIRED'     => '#22c55e',
	'SHADOW'    => '#3b82f6',
	'CONVERTED' => '#f59e0b',
	'ABANDONED' => '#64748b',
);
$chart_status_labels = wp_json_encode( array_keys( $status_dist ) );
$chart_status_data   = wp_json_encode( array_values( $status_dist ) );
$chart_status_colors = wp_json_encode( array_values( array_map( fn( $s ) => $status_colors[ $s ] ?? '#475569', array_keys( $status_dist ) ) ) );

$chart_gate_labels = wp_json_encode( array_map( fn( $g ) => 'Gate ' . $g, array_keys( $gate_dist ) ) );
$chart_gate_data   = wp_json_encode( array_values( $gate_dist ) );

/* ── 24 Signal definitions ───────────────────────────────────────────────── */
$signal_defs = array(
	'timing_confidence'         => array(
		'label' => 'Timing Confidence',
		'max'   => 5,
	),
	'price_sensitivity_score'   => array(
		'label' => 'Price Sensitivity',
		'max'   => 5,
	),
	'inventory_pressure'        => array(
		'label' => 'Inventory Pressure',
		'max'   => 5,
	),
	'loyalty_tier'              => array(
		'label' => 'Loyalty Tier',
		'max'   => 5,
	),
	'streak_engagement'         => array(
		'label' => 'Streak Engagement',
		'max'   => 5,
	),
	'vip_status'                => array(
		'label' => 'VIP Status',
		'max'   => 5,
	),
	'cohort_performance'        => array(
		'label' => 'Cohort Performance',
		'max'   => 5,
	),
	'ltv_score'                 => array(
		'label' => 'LTV Score',
		'max'   => 5,
	),
	'rfm_score'                 => array(
		'label' => 'RFM Score',
		'max'   => 5,
	),
	'anniversary_active'        => array(
		'label' => 'Anniversary Active',
		'max'   => 5,
	),
	'birthday_active'           => array(
		'label' => 'Birthday Active',
		'max'   => 5,
	),
	'post_purchase_eligible'    => array(
		'label' => 'Post Purchase Eligible',
		'max'   => 5,
	),
	'subscription_status'       => array(
		'label' => 'Subscription Status',
		'max'   => 4,
	),
	'subscription_intelligence' => array(
		'label' => 'Subscription Intelligence',
		'max'   => 4,
	),
	'referral_count'            => array(
		'label' => 'Referral Count',
		'max'   => 5,
	),
	'revenue_health'            => array(
		'label' => 'Revenue Health',
		'max'   => 4,
	),
	'attribution_confidence'    => array(
		'label' => 'Attribution Confidence',
		'max'   => 5,
	),
	'multicurrency_active'      => array(
		'label' => 'Multi-Currency Active',
		'max'   => 3,
	),
	'multicurrency_detected'    => array(
		'label' => 'Multi-Currency Detected',
		'max'   => 3,
	),
	'geo_match'                 => array(
		'label' => 'Geo Match',
		'max'   => 4,
	),
	'scheduled_rules_active'    => array(
		'label' => 'Scheduled Rules Active',
		'max'   => 5,
	),
	'white_label_active'        => array(
		'label' => 'White Label Active',
		'max'   => 3,
	),
	'webhook_integrations'      => array(
		'label' => 'Webhook Integrations',
		'max'   => 5,
	),
	'profile_depth'             => array(
		'label' => 'Profile Depth',
		'max'   => 5,
	),
);

$signal_defs_json = wp_json_encode( $signal_defs );

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">🔬 Decision Provenance Log</h1>
		<p class="gt-page-subtitle">
			Full audit trail of every BOGO discount decision — signals that fired,
			gate passed, discount applied, and what happened next.
		</p>
	</div>
	<div style="display:flex;gap:10px;flex-wrap:wrap">
		<button type="button" class="gt-btn gt-btn-ghost"
			onclick="gtDlExportCSV('<?php echo esc_js( $nonce ); ?>')">
			↓ Export CSV
		</button>
		<button type="button" class="gt-btn gt-btn-ghost"
			onclick="gtDlTogglePurge()"
			style="border-color:rgba(239,68,68,0.3);color:#ef4444">
			🗑 Purge Old
		</button>
	</div>
</div>

<?php if ( ! defined( 'GTBOGO_PROVENANCE' ) || ! GTBOGO_PROVENANCE ) : ?>
<div class="gt-notice gt-notice-warn gt-animate-in">
	⚠ Decision Provenance is disabled. Add <code>define('GTBOGO_PROVENANCE', true);</code>
	to <code>wp-config.php</code> to enable full decision logging.
</div>
<?php endif; ?>

<?php if ( ! $has_prov ) : ?>
<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:14px;color:var(--gt-subtle);max-width:480px;margin:0 auto;line-height:1.6">
			The <code>gtbogo_provenance</code> table does not exist yet.
			It is created automatically when the plugin activates with
			<code>GTBOGO_PROVENANCE</code> enabled. Run DB Setup from
			<a href="<?php echo esc_url( admin_url( 'admin.php?page=gt-bogo-engine&tab=system-status' ) ); ?>"
				style="color:var(--gt-red)">System Status</a> to create it now.
		</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
	$fp   = (float) ( $stats['fired_pct'] ?? 0 );
	$bp   = (float) ( $stats['blocked_pct'] ?? 0 );
	$kpis = array(
		array( 'Total Decisions', number_format( $stats['total_decisions'] ), 'var(--gt-white)', 'all time' ),
		array( 'Last 30 Days', number_format( $stats['recent_decisions'] ), '#3b82f6', 'recent activity' ),
		array( 'Fired', number_format( $stats['fired_count'] ), '#22c55e', 'deal applied' ),
		array( 'Blocked', number_format( $stats['blocked_count'] ), '#ef4444', 'suppressed' ),
		array( 'Fire Rate', $fp . '%', $fp >= 70 ? '#22c55e' : ( $fp >= 50 ? '#f59e0b' : '#ef4444' ), '30d window' ),
		array( 'Block Rate', $bp . '%', $bp <= 20 ? '#22c55e' : ( $bp <= 40 ? '#f59e0b' : '#ef4444' ), '30d window' ),
	);
	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[0] === 'Total Decisions' || $k[0] === 'Last 30 Days' || $k[0] === 'Fired' || $k[0] === 'Blocked' ? $k[1] : $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>

<!-- ═══════════════════════════════════════════════════════════════════════════
	CHARTS — Status Distribution + Gate Distribution
════════════════════════════════════════════════════════════════════════════ -->
<div class="gt-animate-in" style="display:grid;grid-template-columns:1fr 1fr;gap:16px;margin-bottom:20px">

	<!-- Status donut -->
	<div class="gt-card">
		<div class="gt-card-header">
			<h2 class="gt-card-title">Decision Status (30 days)</h2>
		</div>
		<div style="height:200px;padding:8px">
			<?php if ( empty( $status_dist ) ) : ?>
			<div style="height:200px;display:flex;align-items:center;justify-content:center;color:var(--gt-subtle);font-size:13px">No data yet</div>
			<?php else : ?>
			<canvas id="gt-dl-status-chart"></canvas>
			<?php endif; ?>
		</div>
	</div>

	<!-- Gate bar chart -->
	<div class="gt-card">
		<div class="gt-card-header">
			<h2 class="gt-card-title">Gate Distribution (30 days)</h2>
			<span style="font-size:11px;color:var(--gt-subtle)">Higher gate = stricter validation</span>
		</div>
		<div style="height:200px;padding:8px">
			<?php if ( empty( $gate_dist ) ) : ?>
			<div style="height:200px;display:flex;align-items:center;justify-content:center;color:var(--gt-subtle);font-size:13px">No data yet</div>
			<?php else : ?>
			<canvas id="gt-dl-gate-chart"></canvas>
			<?php endif; ?>
		</div>
	</div>
</div>

<!-- ═══════════════════════════════════════════════════════════════════════════
	LIVE FEED
════════════════════════════════════════════════════════════════════════════ -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px" id="gt-dl-live-panel">
	<div class="gt-card-header">
		<h2 class="gt-card-title">⚡ Live Decision Feed</h2>
		<div style="display:flex;align-items:center;gap:10px">
			<div style="width:7px;height:7px;border-radius:50%;background:#22c55e;box-shadow:0 0 6px #22c55e;animation:gtp-pulse 2s ease-in-out infinite"></div>
			<span style="font-size:11px;color:var(--gt-subtle)">Auto-refreshes every 30s</span>
			<button onclick="gtDlRefreshLive('<?php echo esc_js( $nonce ); ?>')"
					style="background:none;border:none;color:var(--gt-red);cursor:pointer;font-size:11px;font-family:inherit">
				↻ Now
			</button>
		</div>
	</div>

	<div id="gt-dl-live-feed">
	<?php if ( empty( $live_feed ) ) : ?>
	<div style="padding:20px;text-align:center;color:var(--gt-subtle);font-size:13px">
		No decisions recorded yet. Decisions appear when BOGO rules evaluate on the cart page.
	</div>
		<?php
	else :
		foreach ( $live_feed as $lf ) :
			$st = $lf['status'] ?? 'FIRED';
			$sc = $st === 'FIRED' ? '#22c55e' : ( $st === 'SHADOW' ? '#3b82f6' : '#ef4444' );
			$oc = $lf['outcome'] ?? '';
			?>
	<div class="gt-feed-item" style="display:flex;align-items:center;gap:12px;padding:10px 16px;border-bottom:1px solid rgba(255,255,255,0.04)">
		<span style="padding:2px 8px;border-radius:20px;font-size:9px;font-weight:800;text-transform:uppercase;
					background:<?php echo esc_attr( $sc ); ?>18;border:1px solid <?php echo esc_attr( $sc ); ?>40;
					color:<?php echo esc_attr( $sc ); ?>;flex-shrink:0;letter-spacing:.06em">
			<?php echo esc_html( $st ); ?>
		</span>
		<span style="font-size:12px;font-weight:600;color:var(--gt-white);flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">
			<?php echo esc_html( $lf['rule_id'] ?: '—' ); ?>
		</span>
		<span style="font-size:11px;color:var(--gt-subtle)">PCV <?php echo esc_html( number_format( (float) $lf['pcv_score'], 2 ) ); ?></span>
		<span style="font-size:11px;color:#f59e0b"><?php echo esc_html( (float) $lf['discount_pct'] . '%' ); ?></span>
		<span style="font-size:11px;color:var(--gt-subtle);font-family:'DM Mono','Courier New',monospace">Gate <?php echo esc_html( (string) (int) $lf['gate_passed'] ); ?></span>
			<?php
			if ( $oc ) :
				$oc_color = $oc === 'CONVERTED' ? '#22c55e' : '#64748b';
				?>
		<span style="font-size:10px;color:<?php echo esc_attr( $oc_color ); ?>;font-weight:700"><?php echo esc_html( $oc ); ?></span>
		<?php endif; ?>
		<span class="gt-feed-time" style="font-size:10px;color:rgba(100,116,139,0.6);flex-shrink:0">
					<?php echo esc_html( human_time_diff( strtotime( $lf['created_at'] ), time() ) . ' ago' ); ?>
		</span>
	</div>
			<?php
			endforeach;
endif;
	?>
	</div>
</div>

<!-- ═══════════════════════════════════════════════════════════════════════════
	FILTER BAR
════════════════════════════════════════════════════════════════════════════ -->
<div class="gt-card gt-animate-in" style="margin-bottom:12px">
	<form method="get" action="">
		<input type="hidden" name="page" value="gt-bogo-engine">
		<input type="hidden" name="tab" value="decision-log">
		<div style="display:flex;flex-wrap:wrap;gap:10px;align-items:flex-end">

			<div>
				<label style="font-size:10px;font-weight:700;color:var(--gt-subtle);text-transform:uppercase;letter-spacing:.08em;display:block;margin-bottom:4px">Search</label>
				<input type="text" name="search" value="<?php echo esc_attr( $f_search ); ?>"
						placeholder="Rule ID or Decision ID…"
						style="padding:7px 12px;background:var(--gt-card);border:1px solid var(--gt-border-md);
								border-radius:6px;color:var(--gt-white);font-size:12px;width:190px;font-family:inherit">
			</div>

			<div>
				<label style="font-size:10px;font-weight:700;color:var(--gt-subtle);text-transform:uppercase;letter-spacing:.08em;display:block;margin-bottom:4px">Rule</label>
				<select name="rule_id"
						style="padding:7px 12px;background:var(--gt-card);border:1px solid var(--gt-border-md);
								border-radius:6px;color:var(--gt-white);font-size:12px;font-family:inherit;cursor:pointer;
								min-width:140px">
					<option value="">All Rules</option>
					<?php foreach ( $all_rules as $ar ) : ?>
					<option value="<?php echo esc_attr( (string) $ar['id'] ); ?>" <?php selected( $f_rule, (string) $ar['id'] ); ?>>
						<?php echo esc_html( mb_strimwidth( $ar['name'], 0, 28, '…' ) ); ?>
					</option>
					<?php endforeach; ?>
				</select>
			</div>

			<div>
				<label style="font-size:10px;font-weight:700;color:var(--gt-subtle);text-transform:uppercase;letter-spacing:.08em;display:block;margin-bottom:4px">Status</label>
				<select name="status"
						style="padding:7px 12px;background:var(--gt-card);border:1px solid var(--gt-border-md);
								border-radius:6px;color:var(--gt-white);font-size:12px;font-family:inherit;cursor:pointer">
					<option value="">All Statuses</option>
					<?php foreach ( array( 'FIRED', 'SHADOW', 'BLOCKED', 'CONVERTED', 'ABANDONED' ) as $st ) : ?>
					<option value="<?php echo esc_attr( $st ); ?>" <?php selected( $f_status, $st ); ?>><?php echo esc_html( $st ); ?></option>
					<?php endforeach; ?>
				</select>
			</div>

			<div>
				<label style="font-size:10px;font-weight:700;color:var(--gt-subtle);text-transform:uppercase;letter-spacing:.08em;display:block;margin-bottom:4px">Gate</label>
				<select name="gate"
						style="padding:7px 12px;background:var(--gt-card);border:1px solid var(--gt-border-md);
								border-radius:6px;color:var(--gt-white);font-size:12px;font-family:inherit;cursor:pointer">
					<option value="0">All Gates</option>
					<?php for ( $g = 1;$g <= 3;$g++ ) : ?>
					<option value="<?php echo esc_attr( (string) $g ); ?>" <?php selected( $f_gate, $g ); ?>>Gate <?php echo esc_html( (string) $g ); ?></option>
					<?php endfor; ?>
				</select>
			</div>

			<div>
				<label style="font-size:10px;font-weight:700;color:var(--gt-subtle);text-transform:uppercase;letter-spacing:.08em;display:block;margin-bottom:4px">From</label>
				<input type="date" name="date_from" value="<?php echo esc_attr( $f_from ); ?>"
						style="padding:7px 10px;background:var(--gt-card);border:1px solid var(--gt-border-md);
								border-radius:6px;color:var(--gt-white);font-size:12px;font-family:inherit">
			</div>

			<div>
				<label style="font-size:10px;font-weight:700;color:var(--gt-subtle);text-transform:uppercase;letter-spacing:.08em;display:block;margin-bottom:4px">To</label>
				<input type="date" name="date_to" value="<?php echo esc_attr( $f_to ); ?>"
						style="padding:7px 10px;background:var(--gt-card);border:1px solid var(--gt-border-md);
								border-radius:6px;color:var(--gt-white);font-size:12px;font-family:inherit">
			</div>

			<div style="display:flex;gap:6px">
				<button type="submit" class="gt-btn gt-btn-primary gt-btn-sm">Filter</button>
				<a href="<?php echo esc_url( admin_url( 'admin.php?page=gt-bogo-engine&tab=decision-log' ) ); ?>"
					class="gt-btn gt-btn-ghost gt-btn-sm">Reset</a>
			</div>

			<?php if ( $total_rows > 0 ) : ?>
			<div style="margin-left:auto;font-size:12px;color:var(--gt-subtle);align-self:center">
				<?php echo esc_html( number_format( $total_rows ) ); ?> decisions
				&nbsp;·&nbsp; Page <?php echo esc_html( (string) $paged ); ?> of <?php echo esc_html( (string) $total_pages ); ?>
			</div>
			<?php endif; ?>
		</div>
	</form>
</div>

<!-- ═══════════════════════════════════════════════════════════════════════════
	DECISIONS TABLE
════════════════════════════════════════════════════════════════════════════ -->
<div class="gt-card gt-animate-in" style="overflow:hidden;margin-bottom:20px">

	<?php if ( empty( $decisions ) ) : ?>
	<div style="padding:40px;text-align:center">
		<div style="font-size:36px;margin-bottom:12px">🔍</div>
		<div style="font-size:13px;color:var(--gt-subtle)">
			No decisions match the current filters.
			<a href="<?php echo esc_url( admin_url( 'admin.php?page=gt-bogo-engine&tab=decision-log' ) ); ?>"
				style="color:var(--gt-red)">Clear filters →</a>
		</div>
	</div>
	<?php else : ?>

	<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( 'Decision ID', 'Rule', 'Status', 'Outcome', 'PCV Score', 'Discount', 'Gate', 'Time', '' ) as $col ) : ?>
				<th style="padding:10px 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 ( $decisions as $d ) :
			$d_id = $d['decision_id'] ?? '';
			$rule = $d['rule_id'] ?? '—';
			$st   = $d['status'] ?? 'FIRED';
			$oc   = $d['outcome'] ?? '';
			$pcv  = number_format( (float) ( $d['pcv_score'] ?? 0 ), 3 );
			$disc = number_format( (float) ( $d['discount_pct'] ?? 0 ), 1 ) . '%';
			$gate = (int) ( $d['gate_passed'] ?? 0 );
			$ts   = $d['created_at'] ?? '';

			$st_c        = $st === 'FIRED' ? '#22c55e' : ( $st === 'SHADOW' ? '#3b82f6' : '#ef4444' );
			$oc_c        = $oc === 'CONVERTED' ? '#22c55e' : ( $oc === 'ABANDONED' ? '#64748b' : 'var(--gt-subtle)' );
			$has_signals = ! empty( $d['signal_state'] );
			?>
		<tr style="border-bottom:1px solid rgba(255,255,255,0.03);transition:background .12s"
			onmouseover="this.style.background='rgba(255,255,255,0.02)'"
			onmouseout="this.style.background=''">

			<td style="padding:10px 12px;font-family:'DM Mono','Courier New',monospace;font-size:10px;color:var(--gt-subtle)">
				<?php echo esc_html( substr( $d_id, 0, 12 ) . '…' ); ?>
			</td>
			<td style="padding:10px 12px;color:var(--gt-white);font-weight:600;max-width:160px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">
				<?php echo esc_html( $rule ); ?>
			</td>
			<td style="padding:10px 12px">
				<span style="padding:2px 8px;border-radius:20px;font-size:9px;font-weight:800;text-transform:uppercase;
							background:<?php echo esc_attr( $st_c ); ?>18;border:1px solid <?php echo esc_attr( $st_c ); ?>40;
							color:<?php echo esc_attr( $st_c ); ?>">
					<?php echo esc_html( $st ); ?>
				</span>
			</td>
			<td style="padding:10px 12px;color:<?php echo esc_attr( $oc_c ); ?>;font-weight:<?php echo $oc ? '700' : '400'; ?>">
				<?php echo $oc ? esc_html( $oc ) : '—'; ?>
			</td>
			<td style="padding:10px 12px;color:var(--gt-white);font-variant-numeric:tabular-nums"><?php echo esc_html( $pcv ); ?></td>
			<td style="padding:10px 12px;color:#f59e0b;font-weight:700"><?php echo esc_html( $disc ); ?></td>
			<td style="padding:10px 12px;text-align:center">
				<span style="width:24px;height:24px;border-radius:50%;background:rgba(59,130,246,0.15);
							border:1px solid rgba(59,130,246,0.3);color:#60a5fa;
							display:inline-flex;align-items:center;justify-content:center;
							font-size:11px;font-weight:800">
					<?php echo esc_html( (string) $gate ); ?>
				</span>
			</td>
			<td style="padding:10px 12px;color:var(--gt-subtle);font-size:11px;white-space:nowrap">
				<?php echo esc_html( $ts ? human_time_diff( strtotime( $ts ), time() ) . ' ago' : '—' ); ?>
			</td>
			<td style="padding:10px 12px">
				<?php if ( $has_signals ) : ?>
				<button type="button"
					onclick="gtDlToggleSignals(this, <?php echo esc_attr( wp_json_encode( $d['signal_state'] ) ); ?>)"
					style="padding:4px 10px;background:rgba(255,255,255,0.04);border:1px solid var(--gt-border-md);
							border-radius:5px;color:var(--gt-subtle);cursor:pointer;font-size:11px;font-family:inherit">
					▸ Signals
				</button>
				<?php endif; ?>
			</td>
		</tr>
		<!-- Signal accordion row -->
		<tr class="gt-dl-signal-row" style="display:none;background:rgba(255,255,255,0.015)">
			<td colspan="9" style="padding:0">
				<div class="gt-dl-signal-content" style="padding:16px;border-top:1px solid var(--gt-border)"></div>
			</td>
		</tr>
		<?php endforeach; ?>
		</tbody>
	</table>
	</div>

	<!-- Pagination -->
		<?php if ( $total_pages > 1 ) : ?>
	<div style="display:flex;align-items:center;gap:8px;padding:14px 16px;border-top:1px solid var(--gt-border);flex-wrap:wrap">
			<?php if ( $paged > 1 ) : ?>
		<a href="<?php echo esc_url( add_query_arg( 'paged', $paged - 1 ) ); ?>"
			class="gt-btn gt-btn-ghost gt-btn-sm">← Prev</a>
		<?php endif; ?>

			<?php
			$start_p = max( 1, $paged - 2 );
			$end_p   = min( $total_pages, $paged + 2 );
			for ( $p = $start_p; $p <= $end_p; $p++ ) :
				?>
		<a href="<?php echo esc_url( add_query_arg( 'paged', $p ) ); ?>"
			style="padding:5px 12px;border-radius:6px;font-size:12px;font-weight:<?php echo $p === $paged ? '800' : '400'; ?>;
					text-decoration:none;background:<?php echo $p === $paged ? 'var(--gt-red)' : 'rgba(255,255,255,0.04)'; ?>;
					border:1px solid <?php echo $p === $paged ? 'var(--gt-red)' : 'var(--gt-border)'; ?>;
					color:<?php echo $p === $paged ? '#fff' : 'var(--gt-subtle)'; ?>">
				<?php echo esc_html( (string) $p ); ?>
		</a>
			<?php endfor; ?>

			<?php if ( $paged < $total_pages ) : ?>
		<a href="<?php echo esc_url( add_query_arg( 'paged', $paged + 1 ) ); ?>"
			class="gt-btn gt-btn-ghost gt-btn-sm">Next →</a>
		<?php endif; ?>

		<span style="margin-left:auto;font-size:11px;color:var(--gt-subtle)">
			<?php echo esc_html( number_format( $total_rows ) ); ?> total · page <?php echo esc_html( (string) $paged ); ?>/<?php echo esc_html( (string) $total_pages ); ?>
		</span>
	</div>
	<?php endif; ?>

	<?php endif; ?>
</div>

<!-- ═══════════════════════════════════════════════════════════════════════════
	PURGE PANEL (hidden by default)
════════════════════════════════════════════════════════════════════════════ -->
<div id="gt-dl-purge-panel" style="display:none">
	<div class="gt-card gt-animate-in" style="border-color:rgba(239,68,68,0.2);margin-bottom:20px">
		<div class="gt-card-header">
			<h2 class="gt-card-title" style="color:#ef4444">🗑 Purge Old Decisions</h2>
		</div>
		<div style="font-size:13px;color:var(--gt-subtle);margin-bottom:16px;line-height:1.5">
			Delete decision records older than the selected age. This operation cannot be undone.
			The table will be re-indexed automatically after purge.
		</div>
		<div style="display:flex;align-items:center;gap:12px;flex-wrap:wrap">
			<select id="gt-dl-purge-days"
					style="padding:8px 12px;background:var(--gt-card);border:1px solid var(--gt-border-md);
							border-radius:6px;color:var(--gt-white);font-size:13px;font-family:inherit">
				<option value="30">Older than 30 days</option>
				<option value="60">Older than 60 days</option>
				<option value="90" selected>Older than 90 days (recommended)</option>
				<option value="180">Older than 180 days</option>
				<option value="365">Older than 1 year</option>
			</select>
			<button type="button" class="gt-btn"
				style="background:#ef4444"
				onclick="gtDlPurge('<?php echo esc_js( $nonce ); ?>')">
				Confirm Purge
			</button>
			<button type="button" class="gt-btn gt-btn-ghost"
				onclick="gtDlTogglePurge()">Cancel</button>
			<span id="gt-dl-purge-result" style="font-size:12px;color:var(--gt-subtle)"></span>
		</div>
	</div>
</div>

<?php endif; // has_prov ?>

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

var signalDefs = <?php echo $signal_defs_json; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>;

/* ── Chart.js: Status donut ────────────────────────────────────────── */
document.addEventListener('DOMContentLoaded', function() {
	var sCtx = document.getElementById('gt-dl-status-chart');
	if (sCtx) {
		new Chart(sCtx.getContext('2d'), {
			type: 'doughnut',
			data: {
				labels:   <?php echo $chart_status_labels; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>,
				datasets: [{
					data:            <?php echo $chart_status_data; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>,
					backgroundColor: <?php echo $chart_status_colors; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>,
					borderColor:     'transparent',
					hoverOffset:     4,
				}]
			},
			options: {
				responsive:true, maintainAspectRatio:false, cutout:'68%',
				plugins: { legend: { position:'right', labels:{ color:'#64748b', font:{size:11}, boxWidth:12 } } }
			}
		});
	}

	var gCtx = document.getElementById('gt-dl-gate-chart');
	if (gCtx) {
		new Chart(gCtx.getContext('2d'), {
			type: 'bar',
			data: {
				labels:   <?php echo $chart_gate_labels; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>,
				datasets: [{ label:'Decisions', data:<?php echo $chart_gate_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}}}
				}
			}
		});
	}

	/* Auto-refresh live feed every 30s */
	setInterval(function(){
		gtDlRefreshLive('<?php echo esc_js( $nonce ); ?>');
	}, 30000);
});

/* ── Signal accordion ──────────────────────────────────────────────── */
window.gtDlToggleSignals = function(btn, signalJson) {
	var row     = btn.closest('tr');
	var sigRow  = row.nextElementSibling;
	var content = sigRow ? sigRow.querySelector('.gt-dl-signal-content') : null;
	if (!sigRow || !content) return;

	var isOpen = sigRow.style.display !== 'none';
	if (isOpen) { sigRow.style.display = 'none'; btn.textContent = '▸ Signals'; return; }

	btn.textContent = '▾ Close';
	sigRow.style.display = '';

	/* Already rendered? */
	if (content.getAttribute('data-rendered')) return;
	content.setAttribute('data-rendered','1');

	/* Parse signal state */
	var signals = {};
	try { signals = typeof signalJson === 'string' ? JSON.parse(signalJson) : signalJson; } catch(e){}

	/* Build 24 signal bars */
	var html = '<div style="display:grid;grid-template-columns:1fr 1fr;gap:10px">';
	var allSignals = Object.keys(signalDefs).length ? signalDefs : {};
	Object.entries(allSignals).forEach(function(entry) {
		var key = entry[0]; var def = entry[1];
		var val = parseFloat(signals[key] || 0);
		var max = def.max || 5;
		var pct = Math.min(100, Math.round(val / max * 100));
		var col = val >= max*0.7 ? '#ef4444' : (val >= max*0.4 ? '#f59e0b' : (val > 0 ? '#22c55e' : 'rgba(255,255,255,0.1)'));
		html +=
			'<div style="display:flex;align-items:center;gap:8px">' +
			'<div style="width:130px;font-size:10px;color:var(--gt-subtle);flex-shrink:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap" title="'+key+'">'+def.label+'</div>' +
			'<div style="flex:1;height:5px;background:rgba(255,255,255,0.06);border-radius:2px;overflow:hidden">' +
			'<div style="width:'+pct+'%;height:100%;background:'+col+';border-radius:2px;transition:width .8s ease"></div></div>' +
			'<div style="width:28px;text-align:right;font-size:10px;font-weight:700;color:'+col+';font-variant-numeric:tabular-nums">'+val.toFixed(1)+'</div>' +
			'</div>';
	});
	html += '</div>';

	/* If signal_state has keys not in defs, show them too */
	Object.keys(signals).forEach(function(k) {
		if (signalDefs[k]) return;
		var v = parseFloat(signals[k]||0);
		html += '<div style="font-size:10px;color:var(--gt-subtle);margin-top:4px">'+k+': '+v.toFixed(2)+'</div>';
	});

	content.innerHTML = html;

	/* Animate bars after render */
	setTimeout(function(){
		content.querySelectorAll('[style*="transition:width"]').forEach(function(el){
			var w = el.style.width; el.style.width='0%';
			setTimeout(function(){ el.style.width=w; },20);
		});
	},50);
};

/* ── Live feed refresh ─────────────────────────────────────────────── */
window.gtDlRefreshLive = function(nonce) {
	var fd = new FormData();
	fd.append('action','gtbogo_dl_live_feed');
	fd.append('nonce', nonce);
	fetch(ajaxurl,{method:'POST',body:fd})
		.then(function(r){return r.json();})
		.then(function(resp){
			if (resp.success && resp.data.html) {
				var feed = document.getElementById('gt-dl-live-feed');
				if (feed) feed.innerHTML = resp.data.html;
			}
		})
		.catch(function(){});
};

/* ── Export CSV ────────────────────────────────────────────────────── */
window.gtDlExportCSV = function(nonce) {
	var params = new URLSearchParams(window.location.search);
	params.set('action','gtbogo_dl_export_csv');
	params.set('nonce', nonce);
	window.open(ajaxurl+'?'+params.toString(),'_blank');
};

/* ── Purge panel toggle ────────────────────────────────────────────── */
window.gtDlTogglePurge = function() {
	var panel = document.getElementById('gt-dl-purge-panel');
	if (panel) panel.style.display = panel.style.display==='none'?'block':'none';
};

/* ── Purge ─────────────────────────────────────────────────────────── */
window.gtDlPurge = function(nonce) {
	var days   = document.getElementById('gt-dl-purge-days')?.value || 90;
	var result = document.getElementById('gt-dl-purge-result');
	if (!confirm('Delete all decisions older than '+days+' days? This cannot be undone.')) return;

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

	fetch(ajaxurl,{method:'POST',body:fd})
		.then(function(r){return r.json();})
		.then(function(resp){
			if (result) result.textContent = resp.success ? '✓ '+resp.data.message : '✗ '+(resp.data||'Failed');
			if (resp.success) setTimeout(function(){ location.reload(); },1800);
		});
};

})();
</script>

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