<?php
/**
 * Autopilot — Reports v1.3.
 * Now includes: revenue attribution, email open/click rates, conversion table.
 *
 * @var \CartCue\Plugin $plugin
 * @package CartCue
 */
defined( 'ABSPATH' ) || exit;

/* phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound */

use CartCue\Admin\ReportsRepository;

// ---- Revenue (ConversionTracker) -------------------------------------------
$revenue_30d = \CartCue\ConversionTracker::get_revenue( 30 );
$revenue_7d  = \CartCue\ConversionTracker::get_revenue( 7 );
$revenue_all = \CartCue\ConversionTracker::get_revenue( 0 );
$by_play     = \CartCue\ConversionTracker::get_revenue_by_play( 5 );

// ---- Email tracking stats --------------------------------------------------
$email_stats = \CartCue\EmailTracker::get_stats( 0 );

// ---- Log stats (success/error/skipped) ------------------------------------
$report_data   = ReportsRepository::fetch();
$totals        = $report_data['totals'];
$month_success = $report_data['month_success'];
$week_success  = $report_data['week_success'];
$daily_rows    = $report_data['daily_rows'];
$recent_errors = $report_data['recent_errors'];
$wf_rows       = ReportsRepository::fetch_play_metrics();

$chart_data = [];
for ( $i = 29; $i >= 0; $i-- ) {
	$date              = gmdate( 'Y-m-d', strtotime( "-{$i} days" ) );
	$chart_data[$date] = [ 'runs' => 0, 'errors' => 0 ];
}
foreach ( $daily_rows as $row ) {
	if ( isset( $chart_data[ $row['day'] ] ) ) {
		$chart_data[ $row['day'] ] = [ 'runs' => (int)$row['runs'], 'errors' => (int)$row['errors'] ];
	}
}
$max_runs   = max( 1, max( array_column( $chart_data, 'runs' ) ) );
$chart_vals = array_values( $chart_data );
$chart_days = array_keys( $chart_data );
$n  = count( $chart_vals );
$svgW = 860; $svgH = 160; $padL = 36; $padR = 10; $padT = 12; $padB = 26;
$plotW = $svgW - $padL - $padR; $plotH = $svgH - $padT - $padB;
$barW  = max( 4, (int)( $plotW / $n ) - 2 );

// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- set in Admin::render_reports_page().
$active_tab      = isset( $active_tab ) ? $active_tab : 'overview';
$show_campaigns  = $plugin->is_pro();
$reports_base    = add_query_arg( [ 'page' => 'cartcue-reports' ], admin_url( 'admin.php' ) );
if ( ! $show_campaigns && 'campaigns' === $active_tab ) {
	$active_tab = 'overview';
}

$max_active_reports = $plugin->max_active_plays();
$blocked_active_reports = [];
if ( $max_active_reports > 0 ) {
	global $wpdb;
	// phpcs:ignore WordPress.DB.DirectDatabaseQuery
	$active_plays = $wpdb->get_results(
		$wpdb->prepare( 'SELECT id, name, status FROM %i WHERE status = %s ORDER BY id ASC', \CartCue\DB::workflows(), 'active' ),
		ARRAY_A
	) ?: [];
	foreach ( $active_plays as $active_play ) {
		if ( ! $plugin->is_play_allowed_to_run( (int) $active_play['id'] ) ) {
			$blocked_active_reports[] = $active_play;
		}
	}
}
?>
<div class="ap-wrap">
	<div class="ap-page-header">
		<div>
			<h1 class="ap-page-title"><?php esc_html_e( 'Reports', 'cartcue-sales-automation' ); ?></h1>
			<p class="ap-page-sub"><?php echo 'logs' === $active_tab
				? esc_html__( 'Recent automation runs and delivery results.', 'cartcue-sales-automation' )
				: ( 'campaigns' === $active_tab
					? esc_html__( 'Group automations into campaign buckets and track combined impact.', 'cartcue-sales-automation' )
					: esc_html__( 'How your automations are recovering revenue and engaging customers.', 'cartcue-sales-automation' ) );
			?></p>
		</div>
	</div>

	<nav class="ap-reports-tabs" aria-label="<?php esc_attr_e( 'Reports sections', 'cartcue-sales-automation' ); ?>">
		<a href="<?php echo esc_url( $reports_base ); ?>" class="ap-reports-tab<?php echo 'overview' === $active_tab ? ' is-active' : ''; ?>"><?php esc_html_e( 'Overview', 'cartcue-sales-automation' ); ?></a>
		<a href="<?php echo esc_url( add_query_arg( 'tab', 'logs', $reports_base ) ); ?>" class="ap-reports-tab<?php echo 'logs' === $active_tab ? ' is-active' : ''; ?>"><?php esc_html_e( 'Activity Log', 'cartcue-sales-automation' ); ?></a>
		<a href="<?php echo esc_url( add_query_arg( 'tab', 'unsubscribes', $reports_base ) ); ?>" class="ap-reports-tab<?php echo 'unsubscribes' === $active_tab ? ' is-active' : ''; ?>"><?php esc_html_e( 'Unsubscribe Reasons', 'cartcue-sales-automation' ); ?></a>
		<a href="<?php echo esc_url( add_query_arg( 'tab', 'journey', $reports_base ) ); ?>" class="ap-reports-tab<?php echo 'journey' === $active_tab ? ' is-active' : ''; ?>"><?php esc_html_e( 'Customer Journey', 'cartcue-sales-automation' ); ?></a>
		<?php if ( $show_campaigns ) : ?>
		<a href="<?php echo esc_url( add_query_arg( 'tab', 'campaigns', $reports_base ) ); ?>" class="ap-reports-tab<?php echo 'campaigns' === $active_tab ? ' is-active' : ''; ?>"><?php esc_html_e( 'Campaign Groups', 'cartcue-sales-automation' ); ?></a>
		<?php endif; ?>
	</nav>

	<?php if ( ! empty( $blocked_active_reports ) ) : ?>
	<div class="ap-notice-card ap-notice-card--warning">
		<strong><?php esc_html_e( 'Some active automations are not running', 'cartcue-sales-automation' ); ?></strong>
		<p>
			<?php
			echo esc_html(
				sprintf(
					/* translators: %d: maximum active automations that may run on the free plan */
					__( 'Only your %d oldest active automations execute on the free plan. Skipped runs appear in the Activity Log as “Active play limit reached”. Pause an automation or upgrade to run all active automations.', 'cartcue-sales-automation' ),
					$max_active_reports
				)
			);
			?>
			<a href="<?php echo esc_url( add_query_arg( [ 'page' => 'cartcue' ], admin_url( 'admin.php' ) ) ); ?>"><?php esc_html_e( 'View automations', 'cartcue-sales-automation' ); ?></a>
			·
			<a href="<?php echo esc_url( \CartCue\Plugin::upgrade_url( 'active_play_cap_blocked' ) ); ?>" target="_blank" rel="noopener noreferrer"><?php esc_html_e( 'Upgrade to Pro', 'cartcue-sales-automation' ); ?> →</a>
		</p>
		<ul class="ap-overlap-list">
			<?php foreach ( $blocked_active_reports as $blocked_play ) : ?>
			<li><?php echo esc_html( $blocked_play['name'] ?? '' ); ?></li>
			<?php endforeach; ?>
		</ul>
	</div>
	<?php endif; ?>

	<?php if ( 'logs' === $active_tab ) : ?>
		<?php include __DIR__ . '/partials/logs-tab.php'; ?>
	<?php elseif ( 'unsubscribes' === $active_tab ) : ?>
		<?php include __DIR__ . '/partials/unsubscribes-tab.php'; ?>
	<?php elseif ( 'journey' === $active_tab ) : ?>
		<?php include __DIR__ . '/partials/journey-tab.php'; ?>
	<?php elseif ( 'campaigns' === $active_tab ) : ?>
		<?php
		$campaign_stats   = \CartCue\CampaignRepository::fetch_aggregate_stats();
		$campaign_details = null;
		$campaign_id      = isset( $_GET['campaign_id'] ) ? absint( wp_unslash( $_GET['campaign_id'] ) ) : 0; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
		if ( $campaign_id > 0 ) {
			$campaign_details = \CartCue\CampaignRepository::fetch_plays_for_campaign( $campaign_id );
		}
		?>
		<div class="ap-card">
			<div class="ap-card__header"><?php esc_html_e( 'Campaign performance (last 30 days)', 'cartcue-sales-automation' ); ?></div>
			<div class="ap-card__body" style="padding:0">
				<table class="wp-list-table widefat fixed striped" style="border:0">
					<thead>
						<tr>
							<th><?php esc_html_e( 'Campaign', 'cartcue-sales-automation' ); ?></th>
							<th><?php esc_html_e( 'Automations', 'cartcue-sales-automation' ); ?></th>
							<th><?php esc_html_e( 'Emails sent', 'cartcue-sales-automation' ); ?></th>
							<th><?php esc_html_e( 'Open rate', 'cartcue-sales-automation' ); ?></th>
							<th><?php esc_html_e( 'Conversions', 'cartcue-sales-automation' ); ?></th>
							<th><?php esc_html_e( 'Revenue', 'cartcue-sales-automation' ); ?></th>
							<th><?php esc_html_e( 'Actions', 'cartcue-sales-automation' ); ?></th>
						</tr>
					</thead>
					<tbody>
						<?php foreach ( $campaign_stats as $row ) : ?>
							<?php $open_rate = (int) $row['emails_sent'] > 0 ? round( ( (float) $row['opens'] / (int) $row['emails_sent'] ) * 100, 1 ) : 0; ?>
						<tr>
							<td>
								<a href="<?php echo esc_url( add_query_arg( [ 'page' => 'cartcue-reports', 'tab' => 'campaigns', 'campaign_id' => (int) $row['id'] ], admin_url( 'admin.php' ) ) ); ?>">
									<?php echo esc_html( $row['name'] ); ?>
								</a>
							</td>
							<td><?php echo (int) $row['plays']; ?></td>
							<td><?php echo (int) $row['emails_sent']; ?></td>
							<td><?php echo esc_html( $open_rate ); ?>%</td>
							<td><?php echo (int) $row['conversions']; ?></td>
							<td><?php echo wp_kses_post( wc_price( (float) $row['revenue'] ) ); ?></td>
							<td>
								<a href="<?php echo esc_url( wp_nonce_url( add_query_arg( [ 'action' => 'cartcue_delete_campaign', 'campaign_id' => (int) $row['id'] ], admin_url( 'admin-post.php' ) ), 'cartcue_delete_campaign_' . (int) $row['id'] ) ); ?>" class="ap-btn ap-btn-sm" onclick="return confirm('<?php echo esc_js( __( 'Delete this campaign?', 'cartcue-sales-automation' ) ); ?>');">
									<?php esc_html_e( 'Delete', 'cartcue-sales-automation' ); ?>
								</a>
							</td>
						</tr>
						<?php endforeach; ?>
						<?php if ( empty( $campaign_stats ) ) : ?>
						<tr>
							<td colspan="7" style="padding:16px;color:#999;text-align:center"><?php esc_html_e( 'No campaigns yet.', 'cartcue-sales-automation' ); ?></td>
						</tr>
						<?php endif; ?>
					</tbody>
				</table>
			</div>
		</div>

		<?php if ( is_array( $campaign_details ) ) : ?>
		<div class="ap-card" style="margin-top:20px">
			<div class="ap-card__header"><?php esc_html_e( 'Automation breakdown', 'cartcue-sales-automation' ); ?></div>
			<div class="ap-card__body" style="padding:0">
				<table class="wp-list-table widefat fixed striped" style="border:0">
					<thead>
						<tr>
							<th><?php esc_html_e( 'Automation', 'cartcue-sales-automation' ); ?></th>
							<th><?php esc_html_e( 'Trigger', 'cartcue-sales-automation' ); ?></th>
							<th><?php esc_html_e( 'Status', 'cartcue-sales-automation' ); ?></th>
							<th><?php esc_html_e( 'Emails sent', 'cartcue-sales-automation' ); ?></th>
							<th><?php esc_html_e( 'Open rate', 'cartcue-sales-automation' ); ?></th>
							<th><?php esc_html_e( 'Conversions', 'cartcue-sales-automation' ); ?></th>
							<th><?php esc_html_e( 'Revenue', 'cartcue-sales-automation' ); ?></th>
						</tr>
					</thead>
					<tbody>
						<?php foreach ( $campaign_details as $row ) : ?>
							<?php $open_rate = (int) $row['emails_sent'] > 0 ? round( ( (float) $row['opens'] / (int) $row['emails_sent'] ) * 100, 1 ) : 0; ?>
						<tr>
							<td><a href="<?php echo esc_url( add_query_arg( [ 'page' => 'cartcue', 'action' => 'edit', 'id' => (int) $row['id'] ], admin_url( 'admin.php' ) ) ); ?>"><?php echo esc_html( $row['name'] ); ?></a></td>
							<td><?php echo esc_html( $row['trigger_slug'] ); ?></td>
							<td><?php echo esc_html( ucfirst( (string) $row['status'] ) ); ?></td>
							<td><?php echo (int) $row['emails_sent']; ?></td>
							<td><?php echo esc_html( $open_rate ); ?>%</td>
							<td><?php echo (int) $row['conversions']; ?></td>
							<td><?php echo wp_kses_post( wc_price( (float) $row['revenue'] ) ); ?></td>
						</tr>
						<?php endforeach; ?>
						<?php if ( empty( $campaign_details ) ) : ?>
						<tr>
							<td colspan="7" style="padding:16px;color:#999;text-align:center"><?php esc_html_e( 'No automations in this campaign.', 'cartcue-sales-automation' ); ?></td>
						</tr>
						<?php endif; ?>
					</tbody>
				</table>
			</div>
		</div>
		<?php endif; ?>

		<div class="ap-card" style="margin-top:20px">
			<div class="ap-card__header"><?php esc_html_e( 'Create a campaign', 'cartcue-sales-automation' ); ?></div>
			<div class="ap-card__body">
				<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
					<?php wp_nonce_field( 'cartcue_save_campaign' ); ?>
					<input type="hidden" name="action" value="cartcue_save_campaign">
					<input type="text" name="campaign_name" class="ap-input" style="max-width:420px" placeholder="<?php esc_attr_e( 'Campaign name', 'cartcue-sales-automation' ); ?>" required>
					<textarea name="campaign_description" class="ap-textarea" rows="3" style="max-width:620px;margin-top:10px" placeholder="<?php esc_attr_e( 'Description (optional)', 'cartcue-sales-automation' ); ?>"></textarea>
					<p style="margin-top:10px">
						<button type="submit" class="ap-btn ap-btn-primary"><?php esc_html_e( 'Create', 'cartcue-sales-automation' ); ?></button>
					</p>
				</form>
			</div>
		</div>
	<?php else : ?>

	<!-- Revenue headline -->
	<div class="ap-revenue-headline">
		<span class="ap-revenue-headline__emoji">💰</span>
		<div>
			<div class="ap-revenue-headline__num"><?php echo wp_kses_post( wc_price( $revenue_all ) ); ?></div>
			<div class="ap-revenue-headline__lbl"><?php esc_html_e( 'Total Revenue Recovered', 'cartcue-sales-automation' ); ?></div>
		</div>
	</div>

	<!-- Stat cards -->
	<div class="ap-stats-grid">
		<div class="ap-stat-card">
			<div class="ap-stat-card__val"><?php echo wp_kses_post( wc_price( $revenue_7d ) ); ?></div>
			<div class="ap-stat-card__lbl"><?php esc_html_e( 'Revenue Recovered (7 days)', 'cartcue-sales-automation' ); ?></div>
		</div>
		<div class="ap-stat-card">
			<div class="ap-stat-card__val"><?php echo esc_html( number_format_i18n( $week_success ) ); ?></div>
			<div class="ap-stat-card__lbl"><?php esc_html_e( 'Automations Activated (7 days)', 'cartcue-sales-automation' ); ?></div>
		</div>
		<div class="ap-stat-card">
			<div class="ap-stat-card__val"><?php echo esc_html( $email_stats['open_rate'] ); ?>%</div>
			<div class="ap-stat-card__lbl"><?php esc_html_e( 'Open Rate', 'cartcue-sales-automation' ); ?></div>
		</div>
		<div class="ap-stat-card ap-stat-card--<?php echo (int)$totals['error_count'] > 0 ? 'warn' : 'ok'; ?>">
			<div class="ap-stat-card__val"><?php echo esc_html( number_format_i18n( (int)$totals['error_count'] ) ); ?></div>
			<div class="ap-stat-card__lbl"><?php esc_html_e( 'Needs Attention', 'cartcue-sales-automation' ); ?></div>
		</div>
	</div>

	<!-- Activity chart -->
	<div class="ap-card" style="margin-top:20px">
		<div class="ap-card__header"><?php esc_html_e( 'Daily automation activity (last 30 days)', 'cartcue-sales-automation' ); ?></div>
		<div class="ap-card__body" style="overflow-x:auto">
			<svg viewBox="0 0 <?php echo esc_attr($svgW); ?> <?php echo esc_attr($svgH); ?>"
				 style="width:100%;max-width:<?php echo esc_attr($svgW); ?>px;height:auto;display:block">
				<?php for ( $g = 0; $g <= 3; $g++ ) :
					$gy = $padT + $plotH - (int)($plotH * $g / 3);
					$gv = (int)round($max_runs * $g / 3); ?>
					<line x1="<?php echo esc_attr($padL); ?>" y1="<?php echo esc_attr($gy); ?>"
						  x2="<?php echo esc_attr($svgW-$padR); ?>" y2="<?php echo esc_attr($gy); ?>"
						  stroke="#e8e8e8" stroke-width="1"/>
					<text x="<?php echo esc_attr($padL-4); ?>" y="<?php echo esc_attr($gy+4); ?>"
						  text-anchor="end" fill="#aaa" font-size="10"><?php echo esc_html($gv); ?></text>
				<?php endfor; ?>
				<?php foreach ($chart_vals as $i => $day) :
					$bh = $day['runs']>0 ? max(2,(int)round($plotH*$day['runs']/$max_runs)) : 0;
					$bx = $padL + (int)round($plotW*$i/$n);
					$by = $padT + $plotH - $bh;
					$eh = $day['errors']>0 ? max(2,(int)round($plotH*$day['errors']/$max_runs)) : 0;
					$eby = $padT + $plotH - $eh;
					$show_lbl = (0 === $i % 5) || ($i === $n-1); ?>
					<?php if ($bh>0) : ?>
					<rect x="<?php echo esc_attr($bx); ?>" y="<?php echo esc_attr($by); ?>"
						  width="<?php echo esc_attr($barW); ?>" height="<?php echo esc_attr($bh); ?>"
						  fill="#534AB7" rx="2">
						<title><?php echo esc_attr($chart_days[$i].': '.$day['runs'].' runs'); ?></title>
					</rect>
					<?php endif; if ($eh>0) : ?>
					<rect x="<?php echo esc_attr($bx); ?>" y="<?php echo esc_attr($eby); ?>"
						  width="<?php echo esc_attr($barW); ?>" height="<?php echo esc_attr($eh); ?>"
						  fill="#ef4444" rx="2" opacity="0.9">
						<title><?php echo esc_attr($chart_days[$i].': '.$day['errors'].' errors'); ?></title>
					</rect>
					<?php endif; if ($show_lbl) : ?>
					<text x="<?php echo esc_attr($bx+$barW/2); ?>" y="<?php echo esc_attr($padT+$plotH+18); ?>"
						  text-anchor="middle" fill="#aaa" font-size="10">
						<?php echo esc_html(gmdate('j',strtotime($chart_days[$i]))); ?>
					</text>
					<?php endif; ?>
				<?php endforeach; ?>
				<rect x="<?php echo esc_attr($svgW-150); ?>" y="4" width="8" height="8" fill="#534AB7" rx="1"/>
				<text x="<?php echo esc_attr($svgW-138); ?>" y="12" fill="#666" font-size="10"><?php esc_html_e('Runs','cartcue-sales-automation'); ?></text>
				<rect x="<?php echo esc_attr($svgW-90); ?>" y="4" width="8" height="8" fill="#ef4444" rx="1"/>
				<text x="<?php echo esc_attr($svgW-78); ?>" y="12" fill="#666" font-size="10"><?php esc_html_e('Errors','cartcue-sales-automation'); ?></text>
			</svg>
		</div>
	</div>

	<!-- Two-column: revenue by play + recent errors -->
	<div class="ap-reports-cols">
		<div class="ap-card">
		<div class="ap-card__header"><?php esc_html_e( 'Top Automations Leaderboard', 'cartcue-sales-automation' ); ?></div>
			<div class="ap-card__body" style="padding:0">
				<?php if ( empty( $by_play ) ) : ?>
				<p style="padding:20px;color:#999;margin:0;font-size:13px">
					<?php esc_html_e( 'No attributed revenue yet. Revenue is recorded when a customer who received an automation email places an order within 14 days.', 'cartcue-sales-automation' ); ?>
				</p>
				<?php else : ?>
				<table class="wp-list-table widefat fixed" style="border:0">
					<thead><tr>
						<th><?php esc_html_e( 'Automation', 'cartcue-sales-automation' ); ?></th>
						<th style="text-align:right"><?php esc_html_e( 'Orders', 'cartcue-sales-automation' ); ?></th>
						<th style="text-align:right"><?php esc_html_e( 'Revenue Recovered', 'cartcue-sales-automation' ); ?></th>
					</tr></thead>
					<tbody>
					<?php foreach ($by_play as $row) : ?>
					<tr>
						<td><?php echo esc_html($row['play_name'] ?: __('Unknown','cartcue-sales-automation')); ?></td>
						<td style="text-align:right"><?php echo esc_html(number_format_i18n((int)$row['orders'])); ?></td>
						<td style="text-align:right;font-weight:600;color:#534AB7"><?php echo wp_kses_post( wc_price( $row['revenue'] ) ); ?></td>
					</tr>
					<?php endforeach; ?>
					</tbody>
				</table>
				<?php endif; ?>
			</div>
		</div>
		<div class="ap-card">
			<div class="ap-card__header"><?php esc_html_e( 'Activity Feed', 'cartcue-sales-automation' ); ?></div>
			<div class="ap-card__body" style="padding:0">
				<?php if ( empty( $recent_errors ) ) : ?>
				<p style="padding:20px;color:#999;margin:0;font-size:13px">
					<?php esc_html_e( 'No recent issues.', 'cartcue-sales-automation' ); ?>
				</p>
				<?php else : ?>
				<table class="wp-list-table widefat fixed" style="border:0">
					<thead><tr>
						<th><?php esc_html_e( 'Automation', 'cartcue-sales-automation' ); ?></th>
						<th><?php esc_html_e( 'Customer', 'cartcue-sales-automation' ); ?></th>
						<th><?php esc_html_e( 'Error', 'cartcue-sales-automation' ); ?></th>
					</tr></thead>
					<tbody>
					<?php foreach ($recent_errors as $err) : ?>
					<tr>
						<td style="font-size:12px"><?php echo esc_html($err['workflow_name']); ?></td>
						<td style="font-size:12px"><?php echo esc_html($err['customer_email']); ?></td>
						<td style="font-size:11px;color:#c0392b"><?php echo esc_html($err['message']); ?></td>
					</tr>
					<?php endforeach; ?>
					</tbody>
				</table>
				<?php endif; ?>
			</div>
		</div>

	<!-- Per-play metrics table -->
	<div class="ap-card" style="margin-top:20px">
		<div class="ap-card__header" style="display:flex;justify-content:space-between;align-items:center">
			<span><?php esc_html_e( 'Per Automation Performance', 'cartcue-sales-automation' ); ?></span>
			<a href="<?php echo esc_url( wp_nonce_url( add_query_arg( [ 'page' => 'cartcue-reports', 'cartcue_export_csv' => '1' ], admin_url( 'admin.php' ) ), 'cartcue_export_logs_csv' ) ); ?>" class="ap-btn">
				⬇ <?php esc_html_e( 'Export CSV', 'cartcue-sales-automation' ); ?>
			</a>
		</div>
		<div class="ap-card__body" style="padding:0">
			<table class="wp-list-table widefat fixed" style="border:0">
				<thead><tr>
					<th><?php esc_html_e( 'Automation', 'cartcue-sales-automation' ); ?></th>
					<th style="text-align:center"><?php esc_html_e( 'Runs (30d)', 'cartcue-sales-automation' ); ?></th>
					<th style="text-align:center"><?php esc_html_e( 'Open rate', 'cartcue-sales-automation' ); ?></th>
					<th style="text-align:center"><?php esc_html_e( 'Conversions', 'cartcue-sales-automation' ); ?></th>
					<th style="text-align:right"><?php esc_html_e( 'Revenue Recovered', 'cartcue-sales-automation' ); ?></th>
				</tr></thead>
				<tbody>
				<?php
				foreach ( $wf_rows as $row ) :
					$open_rate = $row['sent'] > 0 ? round( ( (float) $row['opens'] / (int) $row['sent'] ) * 100, 1 ) : 0;
				?>
				<tr>
					<td><a href="<?php echo esc_url( add_query_arg( [ 'page' => 'cartcue', 'action' => 'edit', 'id' => (int) $row['id'] ], admin_url( 'admin.php' ) ) ); ?>"><?php echo esc_html( $row['name'] ); ?></a></td>
					<td style="text-align:center"><?php echo esc_html(number_format_i18n((int)$row['runs'])); ?></td>
					<td style="text-align:center"><?php echo $row['sent'] > 0 ? esc_html($open_rate).'%' : '–'; ?></td>
					<td style="text-align:center"><?php echo esc_html(number_format_i18n((int)$row['conversions'])); ?></td>
					<td style="text-align:right;font-weight:<?php echo $row['revenue'] > 0 ? '600' : '400'; ?>;color:<?php echo $row['revenue'] > 0 ? '#534AB7' : 'inherit'; ?>"><?php echo $row['revenue'] > 0 ? wp_kses_post( wc_price( (float) $row['revenue'] ) ) : '–'; ?></td>
				</tr>
				<?php endforeach; ?>
				<?php if (empty($wf_rows)) : ?><tr><td colspan="5" style="padding:16px;color:#999;text-align:center"><?php esc_html_e('No automations yet.','cartcue-sales-automation'); ?></td></tr><?php endif; ?>
				</tbody>
			</table>
		</div>
	</div>
		
	</div>



	<?php endif; ?>
</div>

<?php
/* phpcs:enable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound */
?>