<?php
/**
 * Dashboard Widget — WP Admin dashboard widget for analytics summary.
 *
 * Shows:
 * - Meta EMQ Score
 * - Revenue rescued by server-side tracking (last 30 days)
 * - Server-only events count
 * - High-risk order alert
 * - Dismissible Pro CTA (abandoned cart recovery)
 * - Quick link to CapiFlow Smart dashboard
 *
 * @package CapiFlow
 */

namespace CapiFlow\Core;

defined('ABSPATH') || exit;

class Dashboard_Widget
{

	/**
	 * Register hooks.
	 */
	public function register_hooks(): void
	{
		add_action('wp_dashboard_setup', array($this, 'register_widget'));
	}

	/**
	 * Register the WP dashboard widget.
	 */
	public function register_widget(): void
	{
		if (!current_user_can('manage_woocommerce')) {
			return;
		}

		wp_add_dashboard_widget(
			'capiflow_dashboard_widget',
			/* translators: Plugin name */
			__('CapiFlow — Tracking Summary', 'capiflow'),
			array($this, 'render_widget')
		);
	}

	/**
	 * Render the widget content.
	 *
	 * Sections (in order):
	 *  1. Meta EMQ Score (from Dataset_Quality API cache — async, no page-load delay)
	 *  2. KPI Cards: Rescued Revenue + Server-Only Events (last 30d)
	 *  3. Alert: High-risk orders awaiting review (Pro: reads _capiflow_reputation_level meta)
	 *  4. Dismissible Pro CTA (abandoned cart recovery — WP.org compliant: no pricing)
	 *  5. Footer: Dashboard link + version
	 */
	public function render_widget(): void
	{
		$summary = DB_Manager::get_dashboard_summary(30);
		$teaser = DB_Manager::get_teaser_data();
		$is_pro = License_Manager::is_pro_active();

		// Async EMQ — null if not yet fetched by cron. No blocking API call here.
		// Guard: get_purchase_emq() may not exist yet (added in later version).
		$emq = method_exists(Dataset_Quality::class, 'get_purchase_emq')
			? Dataset_Quality::get_purchase_emq()
			: null;

		$currency = function_exists('get_woocommerce_currency_symbol')
			? get_woocommerce_currency_symbol()
			: '$';

		$rescued_revenue = number_format_i18n((float) $summary['rescued_revenue'], 2);
		$rescued_events = (int) $summary['rescued_events'];
		$total_events = (int) $summary['total_events'];

		// Risky orders — Pro hooks this filter to query _capiflow_reputation_level.
		// FREE: returns 0 (no risk data available without Pro).
		$risky_count = (int) apply_filters( 'capiflow_risky_orders_count', 0 );

		$abandoned_value = number_format_i18n((float) $teaser['total_abandoned_value'], 2);

		// Per-user dismiss — each admin can dismiss independently (WP.org requirement)
		$dismissed_cta = get_user_meta(get_current_user_id(), 'capiflow_widget_cta_dismissed', true);
		?>
		<div class="capiflow-widget" style="font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;font-size:13px;">

			<?php if (0 === $total_events): ?>
				<p style="color:#666;font-size:13px;margin:8px 0;">
					<?php esc_html_e('No tracking data yet. Place a test order to get started.', 'capiflow'); ?>
				</p>
			<?php else: ?>

				<?php /* ── 1. Meta EMQ Score ────────────────────────────────── */ ?>
				<?php if (null !== $emq):
					$emq_color = $emq >= 7 ? '#16a34a' : ($emq >= 5 ? '#f59e0b' : '#dc2626');
					$emq_label = $emq >= 7
						? __('Excellent', 'capiflow')
						: ($emq >= 5 ? __('Good', 'capiflow') : __('Needs Work', 'capiflow'));
					?>
					<div
						style="background:#f8fafc;border-left:3px solid <?php echo esc_attr($emq_color); ?>;padding:8px 12px;border-radius:4px;margin-bottom:10px;display:flex;justify-content:space-between;align-items:center;">
						<div>
							<div style="font-size:10px;color:#6b7280;font-weight:600;text-transform:uppercase;letter-spacing:.5px;">
								<?php esc_html_e('Meta EMQ Score', 'capiflow'); ?>
							</div>
							<div style="font-size:18px;font-weight:700;color:<?php echo esc_attr($emq_color); ?>;">
								<?php echo esc_html($emq); ?>/10
							</div>
						</div>
						<span style="font-size:11px;color:<?php echo esc_attr($emq_color); ?>;font-weight:500;">
							<?php echo esc_html($emq_label); ?>
						</span>
					</div>
				<?php endif; ?>

				<?php /* ── 2. KPI Cards ──────────────────────────────────────── */ ?>
				<div style="display:flex;gap:10px;margin-bottom:10px;">
					<div style="flex:1;background:#f0fdf4;border-left:3px solid #16a34a;padding:8px 10px;border-radius:4px;">
						<div style="font-size:10px;color:#15803d;font-weight:600;text-transform:uppercase;letter-spacing:.5px;">
							<?php esc_html_e('Rescued Revenue (30d)', 'capiflow'); ?>
						</div>
						<div style="font-size:18px;font-weight:700;color:#166534;margin-top:2px;">
							<?php echo esc_html($currency . $rescued_revenue); ?>
						</div>
					</div>
					<div style="flex:1;background:#eff6ff;border-left:3px solid #2563eb;padding:8px 10px;border-radius:4px;">
						<div style="font-size:10px;color:#1d4ed8;font-weight:600;text-transform:uppercase;letter-spacing:.5px;">
							<?php esc_html_e('Server-Only Events (30d)', 'capiflow'); ?>
						</div>
						<div style="font-size:18px;font-weight:700;color:#1e3a8a;margin-top:2px;">
							<?php echo esc_html(number_format_i18n($rescued_events)); ?>
							<?php if ($total_events > 0):
								$pct = round(($rescued_events / $total_events) * 100, 1);
								?>
								<span style="font-size:11px;font-weight:400;color:#60a5fa;">(<?php echo esc_html($pct); ?>%)</span>
							<?php endif; ?>
						</div>
					</div>
				</div>

				<?php /* ── 3. Alerts ─────────────────────────────────────────── */ ?>
				<?php if ($risky_count > 0): ?>
					<div
						style="background:#fff1f2;border-left:3px solid #dc2626;padding:8px 10px;border-radius:4px;margin-bottom:10px;font-size:12px;color:#991b1b;">
						🟡 <?php echo esc_html(
							sprintf(
								/* translators: %d: number of risky orders */
								_n(
									'%d high-risk order awaiting review',
									'%d high-risk orders awaiting review',
									$risky_count,
									'capiflow'
								),
								$risky_count
							)
						); ?>
					</div>
				<?php endif; ?>

			<?php endif; /* end $total_events check */ ?>

			<?php /* ── 4. Dismissible Pro CTA ──────────────────────────────
			  * WP.org Rule 11: No pricing on WC core pages. This is our own
			  * dashboard widget so pricing/CTA is allowed. But we link to
			  * our own settings page, not an external checkout. User can dismiss.
			  */ ?>
			<?php if (!$is_pro && !$dismissed_cta): ?>
				<div class="capiflow-widget-cta"
					style="background:#fefce8;border:1px solid #fbbf24;border-radius:6px;padding:10px 12px;margin-bottom:10px;position:relative;">
					<span class="capiflow-dismiss" data-action="capiflow_dismiss_widget_cta"
						style="position:absolute;top:4px;right:8px;cursor:pointer;color:#92400e;font-size:16px;line-height:1;"
						title="<?php esc_attr_e('Dismiss', 'capiflow'); ?>">&times;</span>
					<div style="font-size:12px;color:#92400e;font-weight:600;margin-bottom:4px;">
						🔒 <?php esc_html_e('Pro Feature: Abandoned Cart Recovery', 'capiflow'); ?>
					</div>
					<div style="font-size:12px;color:#78350f;margin-bottom:6px;">
						<?php
						printf(
							/* translators: %s: currency + abandoned cart value */
							esc_html__('%s in carts abandoned. Recover with SMS via CapiFlow Pro.', 'capiflow'),
							'<strong>' . esc_html($currency . $abandoned_value) . '</strong>'
						);
						?>
					</div>
					<a href="<?php echo esc_url(admin_url('admin.php?page=capiflow-settings')); ?>"
						style="font-size:11px;color:#1d4ed8;text-decoration:none;font-weight:500;">
						<?php esc_html_e('Learn More →', 'capiflow'); ?>
					</a>
				</div>
			<?php endif; ?>

			<?php /* ── 5. Footer links ──────────────────────────────────── */ ?>
			<div style="display:flex;justify-content:space-between;align-items:center;">
				<a href="<?php echo esc_url(admin_url('admin.php?page=capiflow-dashboard')); ?>"
					style="font-size:12px;color:#2563eb;text-decoration:none;font-weight:500;">
					<?php esc_html_e('View Full Dashboard →', 'capiflow'); ?>
				</a>
				<span style="font-size:11px;color:#9ca3af;">
					<?php
					printf(
						/* translators: %s: plugin version */
						esc_html__('CapiFlow v%s', 'capiflow'),
						esc_html(CAPIFLOW_VERSION)
					);
					?>
				</span>
			</div>
		</div>
		<?php
	}
}
