<?php
/**
 * Google Tag Manager Settings Page.
 *
 * Stores the GTM container ID and whether to emit a light dataLayer. The
 * actual injection lives in GtmModule, which reads the static getters here.
 *
 * @package Platform\Helm\Modules\Gtm
 */

declare( strict_types = 1 );

namespace Platform\Helm\Modules\Gtm;

use Platform\Helm\Core\Authorization;

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

final class GtmSettingsPage {

	public const PAGE_SLUG   = 'platform-helm-gtm';
	public const PARENT_SLUG = 'platform-helm';
	private const OPTION      = 'platform_helm_gtm';
	private const NONCE       = 'platform_helm_gtm_settings';

	/** Validated container ID (GTM-XXXXXX) or '' if unset/invalid. */
	public static function container_id(): string {
		$opt = get_option( self::OPTION, [] );
		$id  = is_array( $opt ) ? strtoupper( trim( (string) ( $opt['id'] ?? '' ) ) ) : '';
		return preg_match( '/^GTM-[A-Z0-9]+$/', $id ) ? $id : '';
	}

	public static function datalayer_enabled(): bool {
		$opt = get_option( self::OPTION, [] );
		return is_array( $opt ) && ! empty( $opt['datalayer'] );
	}

	public function register_hooks(): void {
		add_action( 'admin_menu', [ $this, 'register_menu' ], 49 );
		add_action( 'admin_post_platform_helm_gtm_save', [ $this, 'handle_save' ] );
	}

	public function register_menu(): void {
		if ( ! Authorization::is_master_admin() ) {
			return;
		}
		add_submenu_page(
			self::PARENT_SLUG,
			__( 'Tag Manager', 'platform-helm' ),
			__( 'Tag Manager', 'platform-helm' ),
			'manage_options',
			self::PAGE_SLUG,
			[ $this, 'render' ]
		);
	}

	public function handle_save(): void {
		if ( ! Authorization::is_master_admin() ) {
			wp_die( esc_html__( 'Not allowed.', 'platform-helm' ), '', [ 'response' => 403 ] );
		}
		check_admin_referer( self::NONCE );

		$raw   = strtoupper( trim( (string) wp_unslash( $_POST['gtm_id'] ?? '' ) ) ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput
		$valid = preg_match( '/^GTM-[A-Z0-9]+$/', $raw ) ? $raw : '';

		update_option( self::OPTION, [
			'id'        => $valid,
			'datalayer' => ! empty( $_POST['gtm_datalayer'] ),
		], false );

		$arg = ( '' === $valid && '' !== $raw ) ? 'invalid' : 'saved';
		wp_safe_redirect( add_query_arg( [ 'page' => self::PAGE_SLUG, $arg => 1 ], admin_url( 'admin.php' ) ) );
		exit;
	}

	public function render(): void {
		Authorization::require_master_admin();
		$id           = self::container_id();
		$datalayer    = self::datalayer_enabled();
		$body_support = function_exists( 'wp_body_open' ) || (int) get_theme_support( 'wp_body_open' ) === 1;
		?>
		<div class="wrap ph-gsc">
			<h1><?php esc_html_e( 'Google Tag Manager', 'platform-helm' ); ?></h1>
			<p class="ph-gsc-lead"><?php esc_html_e( 'Injects your GTM container the correct way: the script as high as possible in the page head, and the no-script fallback immediately after the body opens. This is the lightweight alternative to a dedicated GTM plugin.', 'platform-helm' ); ?></p>

			<?php if ( isset( $_GET['saved'] ) ) : // phpcs:ignore WordPress.Security.NonceVerification.Recommended ?>
				<div class="notice notice-success inline"><p><?php echo '' !== $id ? esc_html__( 'Saved. Your container is now being injected.', 'platform-helm' ) : esc_html__( 'Saved. Injection is off until a valid container ID is entered.', 'platform-helm' ); ?></p></div>
			<?php endif; ?>
			<?php if ( isset( $_GET['invalid'] ) ) : // phpcs:ignore WordPress.Security.NonceVerification.Recommended ?>
				<div class="notice notice-error inline"><p><?php esc_html_e( 'That does not look like a GTM container ID. It must be in the form GTM-XXXXXX.', 'platform-helm' ); ?></p></div>
			<?php endif; ?>

			<div class="notice notice-warning inline"><p>
				<strong><?php esc_html_e( 'Before you enable this — remove any existing GTM injection.', 'platform-helm' ); ?></strong><br />
				<?php esc_html_e( 'If GTM is already being added by Google Site Kit, a header script, Elementor custom code, or your theme options, you will load the container twice and tags will fire twice (and often late). Remove the old injection first — leaving only this one. Double, late injection is the usual cause of misfiring.', 'platform-helm' ); ?>
			</p></div>

			<?php if ( ! $body_support ) : ?>
				<div class="notice notice-warning inline"><p>
					<?php esc_html_e( 'Heads up: your theme may not support the wp_body_open hook, so the no-script fallback might not output. The main script still loads in the head and works for the ~99% of users with JavaScript on.', 'platform-helm' ); ?>
				</p></div>
			<?php endif; ?>

			<div class="ph-gsc-card">
				<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
					<?php wp_nonce_field( self::NONCE ); ?>
					<input type="hidden" name="action" value="platform_helm_gtm_save" />
					<table class="form-table" role="presentation">
						<tr>
							<th scope="row"><label for="ph-gtm-id"><?php esc_html_e( 'Container ID', 'platform-helm' ); ?></label></th>
							<td>
								<input type="text" id="ph-gtm-id" name="gtm_id" class="regular-text" value="<?php echo esc_attr( $id ); ?>" placeholder="GTM-XXXXXX" />
								<p class="description"><?php esc_html_e( 'Find it in Tag Manager, top bar, next to your container name. Leave blank to turn injection off.', 'platform-helm' ); ?></p>
							</td>
						</tr>
						<tr>
							<th scope="row"><?php esc_html_e( 'Basic dataLayer', 'platform-helm' ); ?></th>
							<td>
								<label><input type="checkbox" name="gtm_datalayer" value="1" <?php checked( $datalayer ); ?> /> <?php esc_html_e( 'Push lightweight page context (page type, post type, logged-in yes/no) before GTM loads.', 'platform-helm' ); ?></label>
								<p class="description"><?php esc_html_e( 'Lets you build triggers in GTM on page type or login state without a heavy plugin. Cheap to compute; safe to leave on.', 'platform-helm' ); ?></p>
							</td>
						</tr>
					</table>
					<p><button type="submit" class="button button-primary"><?php esc_html_e( 'Save', 'platform-helm' ); ?></button>
						<span style="margin-left:10px; color:<?php echo '' !== $id ? '#1a7f37' : '#646970'; ?>;">
							<?php echo '' !== $id ? esc_html( sprintf( /* translators: %s container id */ __( 'Injecting %s', 'platform-helm' ), $id ) ) : esc_html__( 'Not injecting (no valid ID)', 'platform-helm' ); ?>
						</span>
					</p>
				</form>
			</div>

			<p class="ph-gsc-hint"><?php esc_html_e( 'After saving, clear the WP Engine cache, open the site in an incognito window, and use Tag Manager’s Preview mode to confirm the container loads once and fires on page view. Then deploy GA4 inside GTM to start collecting full-funnel data.', 'platform-helm' ); ?></p>
		</div>
		<?php
	}
}
