<?php

/**
 * Free-tier Analytics page - revenue and savings summary totals only; the full per-product breakdown lives in the Pro version of this class.
 *
 * @link       https://nudgesells.com
 * @since      1.0.0
 *
 * @package    NudgeSells
 * @subpackage NudgeSells/admin
 */

if (! defined('ABSPATH')) {
	exit;
}

/**
 * NudgeSells_Admin_Analytics
 *
 * Renders the free-tier Analytics page, showing revenue, savings, and order-count summary cards for a selected date range.
 *
 * @since      1.0.0
 * @package    NudgeSells
 * @subpackage NudgeSells/admin
 * @author     NudgeSells <support@nudgesells.com>
 */
class NudgeSells_Admin_Analytics
{

	/**
	 * Render.
	 *
	 * @return void
	 * @since 1.0.0
	 */
	public static function render()
	{
		if (! current_user_can(NudgeSells_Admin::CAPABILITY)) {
			return;
		}

		$days = isset($_GET['nudgesells_range']) ? absint($_GET['nudgesells_range']) : 30;
		if (! in_array($days, array(7, 30), true)) {
			$days = 30;
		}

		$summary       = NudgeSells_Analytics_Data::get_summary($days);
		$daily_revenue = NudgeSells_Analytics_Data::get_daily_revenue($days);
		$net_gain      = $summary['addon_revenue'] + $summary['upgrade_revenue'] - $summary['total_saved'];
		$net_gain_display = $net_gain < 0 ? '-' . wc_price(abs($net_gain)) : wc_price($net_gain);
		?>
		<div class="wrap nudgesells-wrap">
			<?php NudgeSells_Admin::render_header(__('Analytics', 'nudgesells')); ?>
			<p class="nudgesells-subtitle"><?php esc_html_e('How your add-ons and upgrades are performing across completed orders.', 'nudgesells'); ?></p>

			<ul class="nudgesells-pills">
				<?php foreach (array(7 => __('Last 7 days', 'nudgesells'), 30 => __('Last 30 days', 'nudgesells')) as $range => $label) : ?>
					<li>
						<a href="<?php echo esc_url(add_query_arg('nudgesells_range', $range)); ?>" class="<?php echo $days === $range ? 'current' : ''; ?>"><?php echo esc_html($label); ?></a>
					</li>
				<?php endforeach; ?>
			</ul>

			<div class="nudgesells-stat-grid">
				<div class="nudgesells-stat-card">
					<span class="nudgesells-stat-value"><?php echo wp_kses_post(wc_price($summary['addon_revenue'])); ?></span>
					<span class="nudgesells-stat-label"><?php esc_html_e('Add-on revenue', 'nudgesells'); ?></span>
				</div>
				<div class="nudgesells-stat-card">
					<span class="nudgesells-stat-value"><?php echo wp_kses_post(wc_price($summary['upgrade_revenue'])); ?></span>
					<span class="nudgesells-stat-label"><?php esc_html_e('Upgrade revenue', 'nudgesells'); ?></span>
				</div>
				<div class="nudgesells-stat-card">
					<span class="nudgesells-stat-value"><?php echo esc_html($summary['orders_with_upsell']); ?></span>
					<span class="nudgesells-stat-label"><?php esc_html_e('Orders with an upsell', 'nudgesells'); ?></span>
				</div>
				<div class="nudgesells-stat-card">
					<span class="nudgesells-stat-value"><?php echo wp_kses_post(wc_price($summary['total_saved'])); ?></span>
					<span class="nudgesells-stat-label"><?php esc_html_e('Customer savings given', 'nudgesells'); ?></span>
				</div>
				<div class="nudgesells-stat-card<?php echo $net_gain < 0 ? ' nudgesells-stat-card--negative' : ''; ?>">
					<span class="nudgesells-stat-value"><?php echo wp_kses_post($net_gain_display); ?></span>
					<span class="nudgesells-stat-label"><?php esc_html_e('Net gain', 'nudgesells'); ?></span>
				</div>
			</div>

			<?php self::render_revenue_chart($daily_revenue); ?>
		</div>
<?php
	}

	/**
	 * Render revenue chart.
	 *
	 * Renders a <canvas> and hands the daily revenue data off to Chart.js
	 * via a small inline JSON blob - shared by both the free and Pro
	 * Analytics pages (see admin/js/nudgesells-admin-chart.js).
	 *
	 * @param array $daily_revenue From NudgeSells_Analytics_Data::get_daily_revenue().
	 *
	 * @return void
	 * @since 1.0.0
	 */
	public static function render_revenue_chart(array $daily_revenue)
	{
		$is_pro          = NudgeSells_Pro_Loader::is_active();
		$has_any_revenue = false;
		$labels          = array();
		$addon_series    = array();
		$upgrade_series  = array();

		foreach ($daily_revenue as $day) {
			$labels[]         = date_i18n('M j', strtotime($day['date']));
			$addon_series[]   = (float) $day['addon_revenue'];
			$upgrade_series[] = (float) $day['upgrade_revenue'];
			if ($day['addon_revenue'] > 0 || ($is_pro && $day['upgrade_revenue'] > 0)) {
				$has_any_revenue = true;
			}
		}

		$chart_data = array(
			'labels'         => $labels,
			'addonSeries'    => $addon_series,
			'addonLabel'     => __('Add-ons', 'nudgesells'),
			'currencySymbol' => html_entity_decode(get_woocommerce_currency_symbol(), ENT_QUOTES, 'UTF-8'),
		);

		if ($is_pro) {
			$chart_data['upgradeSeries'] = $upgrade_series;
			$chart_data['upgradeLabel']  = __('Upgrades', 'nudgesells');
		}
	?>
		<div class="nudgesells-card">
			<h2><?php esc_html_e('Revenue over time', 'nudgesells'); ?></h2>
			<?php if (! $has_any_revenue) : ?>
				<p class="description"><?php echo $is_pro ? esc_html__('No add-on or upgrade revenue in this date range yet.', 'nudgesells') : esc_html__('No add-on revenue in this date range yet.', 'nudgesells'); ?></p>
			<?php else : ?>
				<div class="nudgesells-revenue-chart-wrap">
					<canvas id="nudgesells-revenue-chart" role="img" aria-label="<?php echo $is_pro ? esc_attr__('Daily add-on and upgrade revenue chart', 'nudgesells') : esc_attr__('Daily add-on revenue chart', 'nudgesells'); ?>"></canvas>
				</div>
				<script type="application/json" id="nudgesells-revenue-chart-data"><?php echo wp_json_encode($chart_data); ?></script>
			<?php endif; ?>
		</div>
	<?php
	}
}
