<?php
/**
 * File Path: includes/helpers/class-mbs-analytics-manager.php
 *
 * My Book Showroom — Analytics Manager
 *
 * Injects third-party analytics script tags and displays the admin notice
 * when a tracking ID is missing. Extracted from MBS_Front_Assets (RF-007)
 * to separate the asset-enqueue concern from analytics concerns.
 *
 * @package MyBookShowroom
 * @since   1.0.0
 */

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

class MBS_Analytics_Manager {

	/**
	 * Register wp_head and admin_notices hooks.
	 *
	 * Called from MBS_Plugin::load_core_services(). Registered at instantiation
	 * to avoid the wp_head priority-1 trap (see MBS_Dark_Mode_Manager).
	 * Priority 20 fires after core script output (priority 10).
	 */
	public function __construct() {
		// Spec 2 (Cookie Analytics): inject GA4 / Plausible tags sitewide when enabled.
		add_action( 'wp_head',      array( $this, 'inject_analytics_head' ), 20 );
		add_action( 'admin_notices', array( $this, 'analytics_admin_notice' ) );
	}

	/**
	 * Inject third-party analytics <script> tags into <head> when enabled.
	 *
	 * Gate: mbs_setting_analytics_enabled must be '1' AND mbs_setting_analytics_id
	 * must decrypt to a non-empty string.
	 *
	 * GA4:      two tags — async external src + inline dataLayer / gtag('config',...)
	 *            block. wp_enqueue_script() is deliberately NOT used for the GA4
	 *            external src because WordPress adds defer, breaking dataLayer order.
	 * Plausible: one deferred external src; tracking ID used as data-domain value.
	 *
	 * Hooked to wp_head at priority 20.
	 *
	 * @return void
	 */
	public function inject_analytics_head(): void {
		if ( '1' !== (string) get_option( 'mbs_setting_analytics_enabled', '' ) ) {
			return;
		}

		$tracking_id  = mbs_decrypt_option( 'mbs_setting_analytics_id' );
		if ( empty( $tracking_id ) ) {
			return;
		}

		$provider = get_option( 'mbs_setting_analytics_provider', 'ga4' );

		if ( 'ga4' === $provider ) {
			$safe_id = esc_js( $tracking_id );
			// phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedScript
			echo '<script async src="https://www.googletagmanager.com/gtag/js?id=' . $safe_id . '"></script>' . "\n"; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped, WordPress.WP.EnqueuedResources.NonEnqueuedScript -- $safe_id / $safe_domain are esc_js() escaped; PHPCS does not recognize esc_js as HTML-output escaper
			// phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedScript
			echo '<script>window.dataLayer=window.dataLayer||[];function gtag(){dataLayer.push(arguments);}gtag("js",new Date());gtag("config","' . $safe_id . '");</script>' . "\n"; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- $safe_id / $safe_domain are esc_js() escaped; PHPCS does not recognize esc_js as HTML-output escaper
		} elseif ( 'plausible' === $provider ) {
			$safe_domain = esc_js( $tracking_id );
			// phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedScript
			echo '<script defer data-domain="' . $safe_domain . '" src="https://plausible.io/js/script.js"></script>' . "\n"; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- $safe_id / $safe_domain are esc_js() escaped; PHPCS does not recognize esc_js as HTML-output escaper
		}
	}

	/**
	 * Show an admin notice when analytics is enabled but no tracking ID is saved.
	 *
	 * Fires on all admin pages; the notice includes a direct link to the
	 * Appearance settings tab.
	 *
	 * Hooked to admin_notices.
	 *
	 * @return void
	 */
	public function analytics_admin_notice(): void {
		if ( '1' !== (string) get_option( 'mbs_setting_analytics_enabled', '' ) ) {
			return;
		}

		$tracking_id  = mbs_decrypt_option( 'mbs_setting_analytics_id' );
		if ( ! empty( $tracking_id ) ) {
			return;
		}

		$settings_url = admin_url( 'admin.php?page=my-book-showroom-settings&tab=advanced' );
		?>
		<div class="notice notice-warning">
			<p><?php printf(
				/* translators: %s: link to MBS appearance settings */
				esc_html__( 'My Book Showroom: Analytics is enabled but no tracking ID has been saved. %s', 'my-book-showroom' ),
				'<a href="' . esc_url( $settings_url ) . '">' . esc_html__( 'Add your tracking ID in Advanced settings.', 'my-book-showroom' ) . '</a>'
			); ?></p>
		</div>
		<?php
	}
}
