<?php
/**
 * Chart Renderer
 *
 * Shared utility for rendering Chart.js charts across all admin screens.
 * Handles script registration and outputs the standard chart container
 * (section wrapper, title, canvas, inline init script) in one call.
 *
 * Usage:
 *   ChartRenderer::render( __( 'Donations', 'ambassadorhub' ), 'myChartId', [
 *       'type' => 'line',
 *       'data' => [ 'labels' => [...], 'datasets' => [...] ],
 *   ] );
 *
 * @package AmbassadorHub\Admin\Charts
 */

namespace AmbassadorHub\Admin\Charts;

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

/**
 * Renders Chart.js charts in admin pages.
 */
final class ChartRenderer {

	/**
	 * Script handle used for Chart.js.
	 */
	const SCRIPT_HANDLE = 'ambh-chartjs';

	/**
	 * Register and enqueue the Chart.js library.
	 *
	 * Safe to call multiple times — WordPress deduplicates enqueues.
	 * Should be called from the page's enqueue_assets() hook callback.
	 *
	 * @return void
	 */
	public static function enqueue(): void {
		if ( ! wp_script_is( self::SCRIPT_HANDLE, 'registered' ) ) {
			wp_register_script(
				self::SCRIPT_HANDLE,
				trailingslashit( AMBASSADOR_HUB_URL ) . 'assets/js/chart.min.js',
				array(),
				'4.5.0',
				true // Load in <head> so it is available when inline init scripts run.
			);
		}

		wp_enqueue_script( self::SCRIPT_HANDLE );
	}

	/**
	 * Render a full chart section.
	 *
	 * Outputs the standard section wrapper with heading, the canvas element,
	 * and an inline <script> that initialises the Chart.js instance.
	 *
	 *
	 * @param string $title     Section heading shown above the chart.
	 * @param string $canvas_id Unique HTML id for the <canvas> element.
	 * @param array  $config    Chart.js config: type, data (labels + datasets), options.
	 * @return void
	 */
	public static function render( string $title, string $canvas_id, array $config ): void {
		// Ensure the library will be loaded (no-op if already enqueued).
		self::enqueue();

		// Force correct aspect-ratio behaviour regardless of caller config.
		$config['options']['maintainAspectRatio'] = false;

		// Encode config and replace raw JS placeholders with unquoted JS expressions.
		$json = (string) wp_json_encode( $config );
		$json = preg_replace( '/"##RAWJS##(.*?)##RAWJS##"/s', '$1', $json );

		?>
		<div class="ambh-dashboard__section">
			<h2 class="ambh-dashboard__section-title">
				<?php echo esc_html( $title ); ?>
			</h2>
			<div class="ambh-dashboard__graph">
				<canvas id="<?php echo esc_attr( $canvas_id ); ?>"></canvas>
			</div>
		</div>
		<?php

		wp_add_inline_script(
			self::SCRIPT_HANDLE,
			'(function () {
				var canvas = document.getElementById( ' . wp_json_encode( $canvas_id ) . ' );
				if ( canvas ) {
					new Chart( canvas, ' . $json . ' );
				}
			})();',
			'after'
		);
	}
}
