<?php
// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals
// phpcs:disable WordPress.Security.NonceVerification
// phpcs:disable WordPress.Security.ValidatedSanitizedInput
// phpcs:disable WordPress.WP.EnqueuedResourceParameters
// phpcs:disable WordPress.DB.PreparedSQL
// phpcs:disable WordPress.DB.PreparedSQLPlaceholders
// phpcs:disable WordPress.DB.DirectDatabaseQuery
// phpcs:disable WordPress.DB.SlowDBQuery
// phpcs:disable PluginCheck.Security.DirectDB
// phpcs:disable PluginCheck.CodeAnalysis
// phpcs:disable WordPressVIPMinimum

/**
 * GT BOGO Engine — Analytics (Enterprise)
 *
 * @package GT_BOGO_Engine
 * @since   3.11.0
 */
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
if ( ! current_user_can( 'manage_options' ) ) {
	return;
}
global $wpdb;

$is_pro = function_exists( 'gt_bogo_has_pro' ) ? gt_bogo_has_pro() : false;

// Date range
$days  = isset( $_GET['days'] ) ? (int) $_GET['days'] : 30;
$days  = in_array( $days, array( 7, 14, 30, 60, 90, 180, 365, 730 ), true ) ? $days : 30;
$start = gmdate( 'Y-m-d H:i:s', strtotime( "-{$days} days" ) );
$prev  = gmdate( 'Y-m-d H:i:s', strtotime( '-' . ( $days * 2 ) . ' days' ) );

// Handle CSV export
if ( isset( $_GET['gtbogo_export_csv'] ) && check_admin_referer( 'gtbogo_export_csv' ) ) {
	$atbl = $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $wpdb->prefix . 'gtbogo_analytics' ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.DirectDatabaseQuery.SchemaChange,WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.PreparedSQL.NotPrepared,PluginCheck.Security.DirectDB.UnescapedDBParameter,WordPress.DB.PreparedSQLPlaceholders.UnnecessaryPrepare
	$rows = $atbl ? $wpdb->get_results(
		$wpdb->prepare( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.DirectDatabaseQuery.SchemaChange,WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.PreparedSQL.NotPrepared,PluginCheck.Security.DirectDB.UnescapedDBParameter,WordPress.DB.PreparedSQLPlaceholders.UnnecessaryPrepare
			"SELECT a.date_created, a.order_id, a.rule_id, COALESCE(r.name, CONCAT('Rule #',a.rule_id)) AS rule_name, a.order_total, a.discount_amount FROM {$wpdb->prefix}gtbogo_analytics a LEFT JOIN {$wpdb->prefix}gtbogo_rules r ON a.rule_id=r.id WHERE a.date_created>=%s ORDER BY a.date_created DESC",
			$start
		),
		ARRAY_A
	) : array();
	header( 'Content-Type: text/csv' );
	header( 'Content-Disposition: attachment; filename="gt-bogo-analytics-' . gmdate( 'Y-m-d' ) . '.csv"' );
	$out = fopen( 'php://output', 'w' );
	fputcsv( $out, array( 'Date', 'Order ID', 'Rule ID', 'Rule Name', 'Order Total', 'Discount Amount' ) );
	foreach ( $rows as $row ) {
		fputcsv( $out, $row );
	}
	fclose( $out ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose
 // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose
	exit;
}

// Analytics data
$atbl = $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $wpdb->prefix . 'gtbogo_analytics' ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.DirectDatabaseQuery.SchemaChange,WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.PreparedSQL.NotPrepared,PluginCheck.Security.DirectDB.UnescapedDBParameter,WordPress.DB.PreparedSQLPlaceholders.UnnecessaryPrepare
if ( $atbl ) {
	$stats      = $wpdb->get_row(
		$wpdb->prepare( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.DirectDatabaseQuery.SchemaChange,WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.PreparedSQL.NotPrepared,PluginCheck.Security.DirectDB.UnescapedDBParameter,WordPress.DB.PreparedSQLPlaceholders.UnnecessaryPrepare
			"SELECT COUNT(DISTINCT order_id) AS orders,
                COALESCE(SUM(order_total),0) AS revenue,
                COALESCE(SUM(discount_amount),0) AS discounts,
                COALESCE(AVG(order_total),0) AS aov,
                COALESCE(MAX(order_total),0) AS max_order,
                COALESCE(MIN(order_total),0) AS min_order
         FROM {$wpdb->prefix}gtbogo_analytics WHERE date_created>=%s",
			$start
		),
		ARRAY_A
	);
	$prev_stats = $wpdb->get_row(
		$wpdb->prepare( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.DirectDatabaseQuery.SchemaChange,WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.PreparedSQL.NotPrepared,PluginCheck.Security.DirectDB.UnescapedDBParameter,WordPress.DB.PreparedSQLPlaceholders.UnnecessaryPrepare
			"SELECT COUNT(DISTINCT order_id) AS orders, COALESCE(SUM(order_total),0) AS revenue
         FROM {$wpdb->prefix}gtbogo_analytics WHERE date_created>=%s AND date_created<%s",
			$prev,
			$start
		),
		ARRAY_A
	);
	// Grain-aware sparkline query (7.1 — daily/weekly/monthly)
	if ( $grain === 'weekly' ) {
		$daily = $wpdb->get_results(
			$wpdb->prepare( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.InterpolatedNotPrepared
				"SELECT DATE_FORMAT(MIN(date_created),'%%Y-W%%v') AS d, COUNT(DISTINCT order_id) AS orders, COALESCE(SUM(order_total),0) AS revenue, COALESCE(SUM(discount_amount),0) AS discounts
				 FROM {$wpdb->prefix}gtbogo_analytics WHERE date_created>=%s GROUP BY YEARWEEK(date_created,3) ORDER BY YEARWEEK(date_created,3) ASC",
				$start
			)
		);
		$yoy_daily = $wpdb->get_results(
			$wpdb->prepare( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.InterpolatedNotPrepared
				"SELECT DATE_FORMAT(MIN(date_created),'%%Y-W%%v') AS d, COUNT(DISTINCT order_id) AS orders, COALESCE(SUM(order_total),0) AS revenue, COALESCE(SUM(discount_amount),0) AS discounts
				 FROM {$wpdb->prefix}gtbogo_analytics WHERE date_created>=%s AND date_created<=%s GROUP BY YEARWEEK(date_created,3) ORDER BY YEARWEEK(date_created,3) ASC",
				$yoy_start, $yoy_end
			)
		);
	} elseif ( $grain === 'monthly' ) {
		$daily = $wpdb->get_results(
			$wpdb->prepare( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.InterpolatedNotPrepared
				"SELECT DATE_FORMAT(date_created,'%%Y-%%m') AS d, COUNT(DISTINCT order_id) AS orders, COALESCE(SUM(order_total),0) AS revenue, COALESCE(SUM(discount_amount),0) AS discounts
				 FROM {$wpdb->prefix}gtbogo_analytics WHERE date_created>=%s GROUP BY DATE_FORMAT(date_created,'%%Y-%%m') ORDER BY d ASC",
				$start
			)
		);
		$yoy_daily = $wpdb->get_results(
			$wpdb->prepare( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.InterpolatedNotPrepared
				"SELECT DATE_FORMAT(date_created,'%%Y-%%m') AS d, COUNT(DISTINCT order_id) AS orders, COALESCE(SUM(order_total),0) AS revenue, COALESCE(SUM(discount_amount),0) AS discounts
				 FROM {$wpdb->prefix}gtbogo_analytics WHERE date_created>=%s AND date_created<=%s GROUP BY DATE_FORMAT(date_created,'%%Y-%%m') ORDER BY d ASC",
				$yoy_start, $yoy_end
			)
		);
	} else {
		$daily = $wpdb->get_results(
			$wpdb->prepare( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.InterpolatedNotPrepared
				"SELECT DATE(date_created) AS d, COUNT(DISTINCT order_id) AS orders, COALESCE(SUM(order_total),0) AS revenue, COALESCE(SUM(discount_amount),0) AS discounts
				 FROM {$wpdb->prefix}gtbogo_analytics WHERE date_created>=%s GROUP BY DATE(date_created) ORDER BY d ASC",
				$start
			)
		);
		$yoy_daily = array();
	}
	$top_rules  = $wpdb->get_results(
		$wpdb->prepare( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.DirectDatabaseQuery.SchemaChange,WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.PreparedSQL.NotPrepared,PluginCheck.Security.DirectDB.UnescapedDBParameter,WordPress.DB.PreparedSQLPlaceholders.UnnecessaryPrepare
			"SELECT COALESCE(r.name, CONCAT('Rule #',a.rule_id)) AS rule_name, COUNT(DISTINCT a.order_id) AS fires, COALESCE(SUM(a.order_total),0) AS revenue, COALESCE(SUM(a.discount_amount),0) AS discount_cost FROM {$wpdb->prefix}gtbogo_analytics a LEFT JOIN {$wpdb->prefix}gtbogo_rules r ON a.rule_id=r.id WHERE a.date_created>=%s GROUP BY a.rule_id ORDER BY fires DESC LIMIT 10",
			$start
		)
	);
	$hourly     = $wpdb->get_results(
		$wpdb->prepare( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.DirectDatabaseQuery.SchemaChange,WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.PreparedSQL.NotPrepared,PluginCheck.Security.DirectDB.UnescapedDBParameter,WordPress.DB.PreparedSQLPlaceholders.UnnecessaryPrepare
			"SELECT HOUR(date_created) AS hr, COUNT(DISTINCT order_id) AS orders
         FROM {$wpdb->prefix}gtbogo_analytics WHERE date_created>=%s GROUP BY HOUR(date_created) ORDER BY hr ASC",
			$start
		)
	);
} else {
	$stats      = array(
		'orders'    => 0,
		'revenue'   => 0,
		'discounts' => 0,
		'aov'       => 0,
		'max_order' => 0,
		'min_order' => 0,
	);
	$prev_stats = array(
		'orders'  => 0,
		'revenue' => 0,
	);
	$daily      = array();
	$top_rules  = array();
	$hourly     = array();
}

// Trend calc
function gt_trend( $now, $prev ) {
	if ( ! $prev || $prev == 0 ) {
		return array(
			'pct' => 0,
			'dir' => 'flat',
		);
	}
	$pct = round( ( ( $now - $prev ) / $prev ) * 100, 1 );
	return array(
		'pct' => abs( $pct ),
		'dir' => $pct > 0 ? 'up' : ( $pct < 0 ? 'down' : 'flat' ),
	);
}
$rev_trend   = gt_trend( $stats['revenue'], $prev_stats['revenue'] );
$order_trend = gt_trend( $stats['orders'], $prev_stats['orders'] );

// Analytics settings save
$message = '';
if ( isset( $_POST['gtbogo_save_analytics_settings'] ) && check_admin_referer( 'gtbogo_analytics_settings' ) ) {
	update_option( 'gtbogo_analytics_enabled', isset( $_POST['analytics_enabled'] ) );
	update_option( 'gtbogo_analytics_track_guests', isset( $_POST['track_guests'] ) );
	update_option( 'gtbogo_analytics_retention_days', intval( $_POST['retention_days'] ?? 365 ) );
	update_option( 'gtbogo_analytics_exclude_roles', array_map( 'sanitize_text_field', (array) ( $_POST['exclude_roles'] ?? array() ) ) );
	$message = 'Analytics settings saved.';
}
$a_enabled   = get_option( 'gtbogo_analytics_enabled', true );
$a_guests    = get_option( 'gtbogo_analytics_track_guests', true );
$a_retention = get_option( 'gtbogo_analytics_retention_days', 365 );
$a_excl      = get_option( 'gtbogo_analytics_exclude_roles', array() );
$wp_roles    = wp_roles()->get_names();

require_once __DIR__ . '/../ui-system/wrapper-start.php';
?>
<div id="gtb-analytics-content">
<div class="gt-page-header gt-animate-in">
	<div>
	<h1 class="gt-page-title">📈 Analytics</h1>
	<p class="gt-page-subtitle">Enterprise campaign performance — revenue influence, rule leaderboard, and time-of-day intelligence</p>
	</div>
	<div class="gt-page-actions" style="display:flex;gap:8px;flex-wrap:wrap;align-items:center">
	<?php
	foreach ( array(
		7   => '7D',
		14  => '14D',
		30  => '30D',
		60  => '60D',
		90  => '90D',
		180 => '6M',
		365 => '1Y',
		730 => '2Y',
	) as $d => $l ) :
		?>
	<a href="?page=gt-bogo-engine&tab=analytics&days=<?php echo esc_html( $d ); ?>&grain=<?php echo esc_attr( $grain ); ?>" class="gt-btn <?php echo $days === $d ? 'gt-btn-primary' : 'gt-btn-ghost'; ?> gt-btn-sm"><?php echo esc_html( $l ); ?></a>
	<?php endforeach; ?>
	<span style="color:var(--gt-border);margin:0 6px">|</span>
	<?php foreach ( array( 'daily' => 'Day', 'weekly' => 'Week', 'monthly' => 'Month' ) as $g => $gl ) : ?>
	<a href="?page=gt-bogo-engine&tab=analytics&days=<?php echo esc_html( $days ); ?>&grain=<?php echo esc_attr( $g ); ?>" class="gt-btn <?php echo $grain === $g ? 'gt-btn-primary' : 'gt-btn-ghost'; ?> gt-btn-sm"><?php echo esc_html( $gl ); ?></a>
	<?php endforeach; ?>
	<a href="
	<?php
	echo esc_url(
		wp_nonce_url(
			add_query_arg(
				array(
					'gtbogo_export_csv' => 1,
					'days'              => $days,
					'page'              => 'gt-bogo-engine',
					'tab'               => 'analytics',
				),
				admin_url( 'admin.php' )
			),
			'gtbogo_export_csv'
		)
	);
	?>
	" class="gt-btn gt-btn-ghost gt-btn-sm">⬇ Export CSV</a>
	</div>
</div>
<?php
if ( $message ) :
	?>
	<div class="gt-notice gt-notice-success gt-animate-in">✓ <?php echo esc_html( $message ); ?></div><?php endif; ?>

<?php if ( ! $a_enabled && $is_pro ) : ?>
<div class="gt-notice gt-animate-in" style="background:rgba(245,158,11,0.08);border-color:rgba(245,158,11,0.3);color:#fcd34d">⚠ Analytics tracking is currently disabled. Enable it in the Settings section below.</div>
<?php endif; ?>

<!-- METRICS -->
<div class="gt-metrics" style="margin-bottom:20px">
	<?php
	$trend_icon = array(
		'up'   => '↑',
		'down' => '↓',
		'flat' => '→',
	);
	$trend_col  = array(
		'up'   => '#86efac',
		'down' => '#fca5a5',
		'flat' => '#94a3b8',
	);
	foreach ( array(
		array( '💰', 'Revenue Influenced', '$' . number_format( (float) $stats['revenue'], 2 ), '#22c55e', $rev_trend, 'Total cart value of orders where a BOGO rule fired' ),
		array( '🛒', 'BOGO Orders', number_format( (int) $stats['orders'] ), '#e10000', $order_trend, 'Unique orders with at least one BOGO discount applied' ),
		array( '🏷️', 'Discount Given', '$' . number_format( (float) $stats['discounts'], 2 ), '#f59e0b', null, 'Sum of all BOGO discounts applied in this period' ),
		array( '💵', 'Avg Order Value', '$' . number_format( (float) $stats['aov'], 2 ), '#3b82f6', null, 'Mean order value for BOGO-influenced orders' ),
		array( '📦', 'Largest Order', '$' . number_format( (float) $stats['max_order'], 2 ), '#8b5cf6', null, 'Highest single order value in this period' ),
		array( '📊', 'Discount Rate', ( ( $stats['revenue'] > 0 ) ? round( ( $stats['discounts'] / $stats['revenue'] ) * 100, 1 ) : 0 ) . '%', '#64748b', null, 'Discounts as a % of influenced revenue — keep under 25%' ),
	) as $m ) :
		?>
	<div class="gt-metric gt-animate-in" style="--gt-metric-c:<?php echo esc_html( $m[3] ); ?>;position:relative" title="<?php echo esc_attr( $m[5] ); ?>">
	<span class="gt-metric-icon"><?php echo esc_html( $m[0] ); ?></span>
	<div class="gt-metric-label"><?php echo esc_html( $m[1] ); ?></div>
	<div class="gt-metric-value"><?php echo esc_html( $m[2] ); ?></div>
		<?php if ( $m[4] ) : ?>
	<div class="gt-metric-trend" style="color:<?php echo esc_attr( $trend_col[ $m[4]['dir'] ] ); ?>">
			<?php echo esc_html( $trend_icon[ $m[4]['dir'] ] ); ?> <?php echo esc_html( $m[4]['pct'] ); ?>% vs prior period
	</div>
	<?php else : ?>
	<div class="gt-metric-trend">Last <?php echo esc_html( $days ); ?> days</div>
	<?php endif; ?>
	</div>
	<?php endforeach; ?>
</div>

<!-- DAILY CHART -->
<?php if ( ! empty( $daily ) ) : ?>
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
	<div class="gt-card-header">
	<h2 class="gt-card-title">📊 Daily Performance</h2>
	<div style="display:flex;gap:8px">
		<button onclick="gtChart('revenue')" id="btn-rev" class="gt-btn gt-btn-primary gt-btn-sm">Revenue</button>
		<button onclick="gtChart('orders')" id="btn-ord" class="gt-btn gt-btn-ghost gt-btn-sm">Orders</button>
		<button onclick="gtChart('discounts')" id="btn-disc" class="gt-btn gt-btn-ghost gt-btn-sm">Discounts</button>
	</div>
	</div>
	<canvas id="gt-main-chart" height="80"></canvas>
	<script src="https://cdn.jsdelivr.net/npm/chart.js@5.0.0/dist/chart.umd.min.js"></script> <?php // phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedScript, PluginCheck.CodeAnalysis.Offloading.OffloadedContent ?>
	<script>
	var gtDays    = <?php echo wp_json_encode( array_column( (array) $daily, 'd' ) ); ?>;
	var gtRev     = <?php echo wp_json_encode( array_map( 'floatval', array_column( (array) $daily, 'revenue' ) ) ); ?>;
	var gtOrd     = <?php echo wp_json_encode( array_map( 'intval', array_column( (array) $daily, 'orders' ) ) ); ?>;
	var gtDisc    = <?php echo wp_json_encode( array_map( 'floatval', array_column( (array) $daily, 'discounts' ) ) ); ?>;
	var gtChartObj= null;
	function gtChart(type) {
	var sets = {
		revenue:  {data:gtRev,  label:'Revenue ($)',   color:'#e10000', prefix:'$'},
		orders:   {data:gtOrd,  label:'Orders',        color:'#3b82f6', prefix:''},
		discounts:{data:gtDisc, label:'Discounts ($)',  color:'#f59e0b', prefix:'$'},
	};
	var s = sets[type];
	document.querySelectorAll('#btn-rev,#btn-ord,#btn-disc').forEach(b=>b.className='gt-btn gt-btn-ghost gt-btn-sm');
	var map={'revenue':'btn-rev','orders':'btn-ord','discounts':'btn-disc'};
	document.getElementById(map[type]).className='gt-btn gt-btn-primary gt-btn-sm';
	if (gtChartObj) gtChartObj.destroy();
	var ctx = document.getElementById('gt-main-chart').getContext('2d');
	gtChartObj = new Chart(ctx, {
		type:'line',
		data:{labels:gtDays,datasets:[{label:s.label,data:s.data,borderColor:s.color,backgroundColor:s.color.replace(')',',0.08)').replace('rgb','rgba'),borderWidth:2,fill:true,tension:0.4,pointBackgroundColor:s.color,pointRadius:3,pointHoverRadius:5}]},
		options:{responsive:true,plugins:{legend:{display:false},tooltip:{callbacks:{label:function(c){return s.prefix+c.parsed.y.toFixed(s.prefix?2:0);}}}},scales:{x:{grid:{color:'rgba(255,255,255,0.04)'},ticks:{color:'#64748b',font:{size:11}}},y:{grid:{color:'rgba(255,255,255,0.04)'},ticks:{color:'#64748b',font:{size:11},callback:function(v){return s.prefix+v;}}}}}
	});
	}
	gtChart('revenue');
	</script>
</div>
<?php endif; ?>

<!-- RULE LEADERBOARD + HOURLY HEATMAP -->
<div style="display:grid;grid-template-columns:1.4fr 1fr;gap:20px;margin-bottom:20px">

<!-- Rule Leaderboard -->
<div class="gt-card gt-animate-in">
	<div class="gt-card-header"><h2 class="gt-card-title">🏆 Rule Performance Leaderboard</h2><span class="gt-text-soft" style="font-size:13px">Last <?php echo esc_html( $days ); ?> days</span></div>
	<?php if ( ! empty( $top_rules ) ) : ?>
	<div style="overflow-x:auto">
	<table class="gt-table">
		<thead><tr><th>#</th><th>Rule</th><th>Fires</th><th>Revenue</th><th>Discount</th><th>Efficiency</th></tr></thead>
		<tbody>
		<?php
		foreach ( $top_rules as $i => $rule ) :
			$efficiency = $rule->revenue > 0 ? round( ( $rule->revenue - $rule->discount_cost ) / $rule->revenue * 100, 1 ) : 0;
			$eff_color  = $efficiency > 80 ? '#86efac' : ( $efficiency > 60 ? '#fcd34d' : '#fca5a5' );
			?>
		<tr>
		<td style="font-weight:800;color:<?php echo esc_attr( $i === 0 ? '#fcd34d' : ( $i === 1 ? '#94a3b8' : ( $i === 2 ? '#d97706' : 'var(--gt-subtle)' ) ) ); ?>"><?php echo esc_html( $i + 1 ); ?></td>
		<td style="font-weight:600;color:var(--gt-white)"><?php echo esc_html( $rule->rule_name ?: 'Unnamed Rule' ); ?></td>
		<td style="font-family:'DM Mono',monospace;color:var(--gt-white)"><?php echo esc_html( number_format( $rule->fires ) ); ?></td>
		<td style="font-family:'DM Mono',monospace;color:#86efac">$<?php echo esc_html( number_format( $rule->revenue, 2 ) ); ?></td>
		<td style="font-family:'DM Mono',monospace;color:#fca5a5">-$<?php echo esc_html( number_format( $rule->discount_cost, 2 ) ); ?></td>
		<td><span style="font-size:13px;font-weight:700;color:<?php echo esc_html( $eff_color ); ?>"><?php echo esc_html( $efficiency ); ?>%</span></td>
		</tr>
		<?php endforeach; ?>
		</tbody>
	</table>
	</div>
	<div style="margin-top:12px;padding:10px 14px;background:rgba(59,130,246,0.05);border-radius:8px;font-size:13px;color:var(--gt-soft)">
	💡 <strong style="color:var(--gt-white)">Efficiency</strong> = (Revenue − Discount) ÷ Revenue. Above 80% is excellent. Below 60% means the discount is too aggressive for the volume it drives.
	</div>
	<?php else : ?>
	<div style="text-align:center;padding:40px 24px">
	<div style="font-size:40px;margin-bottom:12px">🏆</div>
	<p class="gt-text-soft" style="font-size:13px">No rule data yet. Rules will appear here once customers trigger BOGO discounts.</p>
	</div>
	<?php endif; ?>
</div>

<!-- Time-of-Day Heatmap -->
<div class="gt-card gt-animate-in">
	<div class="gt-card-header"><h2 class="gt-card-title">⏰ Peak Hours</h2><span class="gt-text-soft" style="font-size:13px">Orders by hour</span></div>
	<?php
	if ( ! empty( $hourly ) ) :
		$max_h = max( array_column( (array) $hourly, 'orders' ) ) ?: 1;
		$hrs   = array_column( (array) $hourly, 'hr' );
		$ord   = array_column( (array) $hourly, 'orders' );
		?>
	<div style="display:flex;flex-direction:column;gap:6px">
		<?php
		foreach ( $hourly as $h ) :
			$pct     = round( ( $h->orders / $max_h ) * 100 );
			$label   = sprintf( '%02d:00', $h->hr );
			$is_peak = $h->orders == $max_h;
			?>
	<div style="display:flex;align-items:center;gap:10px">
		<span style="font-size:13px;font-family:'DM Mono',monospace;color:var(--gt-subtle);min-width:40px"><?php echo esc_html( $label ); ?></span>
		<div style="flex:1;height:18px;background:rgba(255,255,255,0.04);border-radius:4px;overflow:hidden">
		<div style="height:100%;width:<?php echo esc_html( $pct ); ?>%;background:<?php echo esc_html( $is_peak ) ? '#e10000' : 'rgba(225,0,0,0.4)'; ?>;border-radius:4px;transition:width 0.8s"></div>
		</div>
		<span style="font-size:13px;font-family:'DM Mono',monospace;color:<?php echo esc_html( $is_peak ) ? '#fff' : 'var(--gt-soft)'; ?>;min-width:24px;text-align:right"><?php echo esc_html( $h->orders ); ?></span>
			<?php
			if ( $is_peak ) :
				?>
				<span style="font-size:13px;color:#e10000;font-weight:700">PEAK</span><?php endif; ?>
	</div>
		<?php endforeach; ?>
	</div>
	<div style="margin-top:16px;padding:10px 14px;background:rgba(255,255,255,0.03);border-radius:8px;font-size:13px;color:var(--gt-soft)">
	💡 Use peak hours to time your Campaign Scheduler — schedule flash deals to start 2 hours before your peak and expire at peak end for maximum urgency.
	</div>
		<?php else : ?>
	<div style="text-align:center;padding:40px 24px">
	<div style="font-size:40px;margin-bottom:12px">⏰</div>
	<p class="gt-text-soft" style="font-size:13px">Hourly data will populate once orders start coming in.</p>
	</div>
	<?php endif; ?>
</div>
</div>

<!-- ANALYTICS SETTINGS -->
<?php if ( $is_pro ) : ?>
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
	<div class="gt-card-header"><h2 class="gt-card-title">⚙️ Analytics Configuration</h2></div>
	<form method="post" action="">
	<?php wp_nonce_field( 'gtbogo_analytics_settings' ); ?>
	<div class="gt-setting-row">
		<div><div class="gt-setting-label">Enable Analytics Tracking</div><div class="gt-setting-desc">Record order data when BOGO rules fire. Disable only if you use a separate analytics platform and want to reduce DB writes.</div></div>
		<label class="gt-toggle"><input type="checkbox" name="analytics_enabled" value="1" <?php checked( $a_enabled ); ?> data-option="gtbogo_analytics_enabled" data-nonce="<?php echo esc_attr( wp_create_nonce( 'gtbogo_system_toggle' ) ); ?>"><span class="gt-toggle-track"><span class="gt-toggle-thumb"></span></span></label>
	</div>
	<div class="gt-setting-row">
		<div><div class="gt-setting-label">Track Guest Orders</div><div class="gt-setting-desc">Include guest checkout orders in analytics. Disable to track logged-in customers only.</div></div>
		<label class="gt-toggle"><input type="checkbox" name="track_guests" value="1" <?php checked( $a_guests ); ?>><span class="gt-toggle-track"><span class="gt-toggle-thumb"></span></span></label>
	</div>
	<div class="gt-setting-row">
		<div><div class="gt-setting-label">Data Retention (Days)</div><div class="gt-setting-desc">Analytics records older than this are automatically purged. Recommended: 365 days. Minimum: 30 days.</div></div>
		<input type="number" name="retention_days" class="gt-input" style="width:100px" value="<?php echo esc_attr( $a_retention ); ?>" min="30" max="1825" id="gtbogo_retention_days" aria-label="Retention Days">
	</div>
	<div class="gt-setting-row" style="border:none">
		<div><div class="gt-setting-label">Exclude User Roles from Tracking</div><div class="gt-setting-desc">Orders placed by these roles will not be recorded in analytics. Useful for excluding admin test orders.</div></div>
		<div style="display:flex;gap:10px;flex-wrap:wrap">
		<?php foreach ( $wp_roles as $role_slug => $role_name ) : ?>
		<label style="display:flex;align-items:center;gap:6px;font-size:13px;color:var(--gt-soft);cursor:pointer">
			<input type="checkbox" name="exclude_roles[]" value="<?php echo esc_attr( $role_slug ); ?>" <?php checked( in_array( $role_slug, (array) $a_excl ) ); ?> style="accent-color:var(--gt-red)">
			<?php echo esc_html( $role_name ); ?>
		</label>
		<?php endforeach; ?>
		</div>
	</div>
	<div style="margin-top:20px;text-align:right">
		<button type="submit" name="gtbogo_save_analytics_settings" class="gt-btn gt-btn-primary" style="padding:12px 32px">💾 Save Analytics Settings</button>
	</div>
	</form>
</div>
<?php endif; ?>

<!-- GUIDANCE -->
<div class="gt-card gt-animate-in" style="background:linear-gradient(135deg,rgba(59,130,246,0.06),rgba(7,12,28,0));border-color:rgba(59,130,246,0.15)">
	<div class="gt-card-header"><h2 class="gt-card-title">🧠 How to Read These Numbers</h2></div>
	<div class="gt-feature-grid gt-feature-grid--2col">
	<div>
		<div style="font-size:13px;font-weight:700;color:var(--gt-white);margin-bottom:6px">Revenue Influenced vs Incremental Revenue</div>
		<div style="font-size:13px;color:var(--gt-soft);line-height:1.7">Revenue Influenced tracks all orders where a rule fired — including orders that may have happened without the promotion. To isolate true incremental lift, compare BOGO order volume to your baseline period in the prior month using the prior-period trend arrows above.</div>
	</div>
	<div>
		<div style="font-size:13px;font-weight:700;color:var(--gt-white);margin-bottom:6px">The Discount Rate Warning Zone</div>
		<div style="font-size:13px;color:var(--gt-soft);line-height:1.7">A discount rate above 25% means you are giving away more than a quarter of every influenced sale. This is only sustainable if your gross margin exceeds 50%. If your margin is 35–40%, keep discount rate under 18% to remain profitable on promotion-influenced orders.</div>
	</div>
	<div>
		<div style="font-size:13px;font-weight:700;color:var(--gt-white);margin-bottom:6px">Rule Efficiency Score</div>
		<div style="font-size:13px;color:var(--gt-soft);line-height:1.7">The leaderboard Efficiency % measures how much revenue survives after discounts. An 85% efficiency on a rule that fires 200 times beats a 95% efficiency rule that fires 10 times. Prioritise volume × efficiency, not efficiency alone.</div>
	</div>
	<div>
		<div style="font-size:13px;font-weight:700;color:var(--gt-white);margin-bottom:6px">Acting on Peak Hour Data</div>
		<div style="font-size:13px;color:var(--gt-soft);line-height:1.7">If your peak is consistently between 7pm–9pm, schedule flash deals to start at 6pm and expire at 10pm. Customers who were already shopping in that window will see the deal as serendipitous rather than manufactured, which dramatically improves conversion rates compared to campaigns that run all day.</div>
	</div>
	</div>
</div>

</div><!-- #gtb-analytics-content -->

<script>
(function() {
	var cid = 'gtb-analytics-content';

	// ── Auto-refresh analytics every 60 seconds ──────────────────────────────
	function gtbRefreshAnalytics() {
		var content = document.getElementById(cid);
		if (!content) return;
		var href = window.location.href;
		if (href.indexOf('tab=analytics') === -1) return;
		fetch(href, {credentials:'same-origin'})
			.then(function(r){ return r.text(); })
			.then(function(html){
				var doc2 = new DOMParser().parseFromString(html,'text/html');
				var nc = doc2.getElementById(cid);
				if (nc) {
					content.innerHTML = nc.innerHTML;
					// Re-mark links after refresh
					content.querySelectorAll('a[href*="tab=analytics"]').forEach(function(a){
						var h = a.getAttribute('href')||'';
						if (/days/.test(h)||h.indexOf('tab=analytics')!==-1) a.classList.add('gtb-inline-link');
					});
				}
			})
			.catch(function(){});
	}
	setInterval(gtbRefreshAnalytics, 60000);

	// Mark all internal filter/nav links for this tab
	document.querySelectorAll('a[href*="tab=analytics"]').forEach(function(a) {
		var href = a.getAttribute('href') || '';
		if (/days/.test(href) || href.indexOf('tab=analytics') !== -1) {
			if (!a.classList.contains('gtb-inline-link')) a.classList.add('gtb-inline-link');
		}
	});
	document.addEventListener('click', function(e) {
		var link = e.target.closest('a.gtb-inline-link');
		if (!link) return;
		var href = link.getAttribute('href') || '';
		if (!href || href.indexOf('#') === 0) return;
		e.preventDefault();
		var content = document.getElementById(cid);
		if (!content) { window.location.href = href; return; }
		content.style.opacity = '0.5';
		content.style.transition = 'opacity 0.1s ease';
		fetch(href, {credentials:'same-origin'})
			.then(function(r) { return r.text(); })
			.then(function(html) {
				var doc2 = new DOMParser().parseFromString(html, 'text/html');
				var nc = doc2.getElementById(cid);
				if (nc) {
					content.innerHTML = nc.innerHTML;
					content.style.opacity = '1';
					history.pushState(null, '', href);
					// Re-mark new links after swap
					content.querySelectorAll('a[href*="tab=analytics"]').forEach(function(a) {
						var h = a.getAttribute('href') || '';
						if (/days/.test(h) || h.indexOf('tab=analytics') !== -1) a.classList.add('gtb-inline-link');
					});
				} else {
					window.location.href = href;
				}
			})
			.catch(function() { window.location.href = href; });
	});
})();
</script>
<?php require_once __DIR__ . '/../ui-system/wrapper-end.php'; ?>
