<?php
namespace AnalyticsIntegration;

use WP_PowerSuite\Core\OptionStoreModuleSettingsRepository;

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

/**
 * Admin UI for Analytics Integration module.
 *
 * @var string $module_id The ID of the current module.
 * @var array  $module_meta The metadata for the current module.
 * @since 1.0.0
 */

if ( ! isset( $module_id ) ) {
	$module_id = 'analytics-integration';
}

if ( ! class_exists( Module::class, false ) && defined( 'WP_POWERSUITE_MODULES_DIR' ) ) {
	$module_file = WP_POWERSUITE_MODULES_DIR . 'analytics-integration' . DIRECTORY_SEPARATOR . 'module.php';
	if ( is_readable( $module_file ) ) {
		require_once $module_file;
	}
}

$stored_settings = OptionStoreModuleSettingsRepository::forModule( $module_id )->all( [] );
if ( ! is_array( $stored_settings ) ) {
	$stored_settings = [];
}

$settings = class_exists( Module::class, false )
	? Module::normalizeSettings( array_merge( Module::getDefaultSettings(), $stored_settings ) )
	: array_merge(
		[
			'ga4_id'               => '',
			'disable_for_admins'   => true,
			'exclude_roles'        => [],
			'disable_on_staging'   => true,
			'exclude_login'        => true,
			'anonymize_ip'         => true,
			'respect_dnt'          => true,
			'consent_mode'         => true,
			'cache_safe_exclusion' => true,
		],
		$stored_settings
	);

$environment         = class_exists( Module::class, false ) ? Module::resolveEnvironment() : wp_get_environment_type();
$ga4_id              = (string) ( $settings['ga4_id'] ?? '' );
$ga4_valid           = class_exists( Module::class, false ) ? Module::isValidGa4Id( $ga4_id ) : (bool) preg_match( '/^G-[A-Z0-9]{10}$/', $ga4_id );
$duplicate_sources   = class_exists( Module::class, false ) ? Module::detectDuplicateSources( $ga4_id ) : [];
$would_track         = class_exists( Module::class, false ) ? Module::wouldTrackForSettings( $settings ) : false;
$selected_roles      = is_array( $settings['exclude_roles'] ?? null ) ? $settings['exclude_roles'] : [];
$all_roles           = function_exists( 'wp_roles' ) ? wp_roles()->get_names() : [];
$tracking_disabled   = ! empty( $settings['disable_on_staging'] ) && class_exists( Module::class, false ) && Module::isNonProductionEnvironment();

?>
<div class="wp-powersuite-module-settings">
	<p class="description">
		<?php esc_html_e( 'Configure Google Analytics 4 pageview tracking. This module injects the official gtag.js snippet with consent-mode defaults, environment guards, and duplicate-tracking prevention.', 'wp-powersuite' ); ?>
	</p>

	<form class="wp-powersuite-module-settings-form" data-module-id="<?php echo esc_attr( $module_id ); ?>" id="analytics-integration-form">
		<?php wp_nonce_field( 'wp_powersuite_save_module_settings_' . $module_id, 'wp_powersuite_nonce' ); ?>

		<h3><?php esc_html_e( 'GA4 Measurement ID', 'wp-powersuite' ); ?></h3>
		<table class="form-table" role="presentation">
			<tbody>
				<tr>
					<th scope="row">
						<label for="ga4_id"><?php esc_html_e( 'Measurement ID', 'wp-powersuite' ); ?></label>
					</th>
					<td>
						<input type="text"
							id="ga4_id"
							name="ga4_id"
							value="<?php echo esc_attr( $ga4_id ); ?>"
							class="regular-text wp-powersuite-advanced-setting"
							data-setting-key="ga4_id"
							placeholder="G-XXXXXXXXXX"
							pattern="G-[A-Z0-9]{10}"
							autocomplete="off"
							spellcheck="false"
						/>
						<p class="description">
							<?php esc_html_e( 'Enter your GA4 Measurement ID (format G-XXXXXXXXXX). Find it in Google Analytics → Admin → Data Streams.', 'wp-powersuite' ); ?>
						</p>
					</td>
				</tr>
			</tbody>
		</table>

		<h3 class="wpps-settings-section-title"><?php esc_html_e( 'Behavior', 'wp-powersuite' ); ?></h3>
		<table class="form-table" role="presentation">
			<tbody>
				<tr>
					<th scope="row"><?php esc_html_e( 'Tracking Controls', 'wp-powersuite' ); ?></th>
					<td>
						<fieldset>
							<label>
								<input type="checkbox"
									name="disable_for_admins"
									value="1"
									<?php checked( ! empty( $settings['disable_for_admins'] ) ); ?>
									class="wp-powersuite-advanced-setting"
									data-setting-key="disable_for_admins"
								/>
								<strong><?php esc_html_e( 'Disable tracking for administrators', 'wp-powersuite' ); ?></strong>
							</label>
							<p class="description wpps-field-indent">
								<?php esc_html_e( 'Skips tracking for logged-in users with the manage_options capability.', 'wp-powersuite' ); ?>
							</p>

							<label class="wpps-field-block">
								<input type="checkbox"
									name="exclude_login"
									value="1"
									<?php checked( ! empty( $settings['exclude_login'] ) ); ?>
									class="wp-powersuite-advanced-setting"
									data-setting-key="exclude_login"
								/>
								<strong><?php esc_html_e( 'Disable tracking on the login screen', 'wp-powersuite' ); ?></strong>
							</label>
							<p class="description wpps-field-indent">
								<?php esc_html_e( 'Prevents analytics from loading on wp-login.php.', 'wp-powersuite' ); ?>
							</p>

							<label class="wpps-field-block">
								<input type="checkbox"
									name="disable_on_staging"
									value="1"
									<?php checked( ! empty( $settings['disable_on_staging'] ) ); ?>
									class="wp-powersuite-advanced-setting"
									data-setting-key="disable_on_staging"
								/>
								<strong><?php esc_html_e( 'Disable tracking on staging/local environments', 'wp-powersuite' ); ?></strong>
							</label>
							<p class="description wpps-field-indent">
								<?php esc_html_e( 'Disables tracking when the environment is staging, local, or development, including common localhost and .local hostnames.', 'wp-powersuite' ); ?>
							</p>

							<label class="wpps-field-block">
								<input type="checkbox"
									name="cache_safe_exclusion"
									value="1"
									<?php checked( ! empty( $settings['cache_safe_exclusion'] ) ); ?>
									class="wp-powersuite-advanced-setting"
									data-setting-key="cache_safe_exclusion"
								/>
								<strong><?php esc_html_e( 'Cache-safe logged-in exclusion', 'wp-powersuite' ); ?></strong>
							</label>
							<p class="description wpps-field-indent">
								<?php esc_html_e( 'Adds a client-side guard for cached pages so logged-in users are less likely to be tracked when role exclusions are enabled. Full-page cache plugins may still require separate cache vary rules.', 'wp-powersuite' ); ?>
							</p>
						</fieldset>
					</td>
				</tr>
				<tr>
					<th scope="row">
						<label><?php esc_html_e( 'Exclude roles', 'wp-powersuite' ); ?></label>
					</th>
					<td>
						<?php if ( empty( $all_roles ) ) : ?>
							<p class="description"><?php esc_html_e( 'No roles found.', 'wp-powersuite' ); ?></p>
						<?php else : ?>
							<fieldset class="wpps-role-checkboxes">
								<?php foreach ( $all_roles as $role_key => $role_label ) : ?>
									<label class="wpps-role-checkboxes__item">
										<input type="checkbox"
											name="exclude_roles[]"
											value="<?php echo esc_attr( $role_key ); ?>"
											<?php checked( in_array( $role_key, $selected_roles, true ) ); ?>
											class="wp-powersuite-advanced-setting"
											data-setting-key="exclude_roles"
										/>
										<?php echo esc_html( translate_user_role( $role_label ) ); ?>
									</label>
								<?php endforeach; ?>
							</fieldset>
							<p class="description">
								<?php esc_html_e( 'Logged-in users with any selected role will not be tracked on uncached requests.', 'wp-powersuite' ); ?>
							</p>
						<?php endif; ?>
					</td>
				</tr>
			</tbody>
		</table>

		<h3 class="wpps-settings-section-title"><?php esc_html_e( 'Privacy & Compliance', 'wp-powersuite' ); ?></h3>
		<table class="form-table" role="presentation">
			<tbody>
				<tr>
					<th scope="row"><?php esc_html_e( 'Privacy Settings', 'wp-powersuite' ); ?></th>
					<td>
						<fieldset>
							<label>
								<input type="checkbox"
									name="consent_mode"
									value="1"
									<?php checked( ! empty( $settings['consent_mode'] ) ); ?>
									class="wp-powersuite-advanced-setting"
									data-setting-key="consent_mode"
								/>
								<strong><?php esc_html_e( 'Enable Google Consent Mode defaults', 'wp-powersuite' ); ?></strong>
							</label>
							<p class="description wpps-field-indent">
								<?php esc_html_e( 'Loads gtag with analytics_storage denied by default, then grants it only when wpps_allow_analytics allows tracking. CMP plugins should hook that filter or call gtag consent update after consent is granted.', 'wp-powersuite' ); ?>
							</p>

							<label class="wpps-field-block">
								<input type="checkbox"
									name="anonymize_ip"
									value="1"
									<?php checked( ! empty( $settings['anonymize_ip'] ) ); ?>
									class="wp-powersuite-advanced-setting"
									data-setting-key="anonymize_ip"
								/>
								<strong><?php esc_html_e( 'Request IP anonymization flag', 'wp-powersuite' ); ?></strong>
							</label>
							<p class="description wpps-field-indent">
								<?php esc_html_e( 'Passes anonymize_ip to gtag config. This is a helper setting only and does not by itself make your site GDPR compliant.', 'wp-powersuite' ); ?>
							</p>

							<label class="wpps-field-block">
								<input type="checkbox"
									name="respect_dnt"
									value="1"
									<?php checked( ! empty( $settings['respect_dnt'] ) ); ?>
									class="wp-powersuite-advanced-setting"
									data-setting-key="respect_dnt"
								/>
								<strong><?php esc_html_e( 'Respect Do Not Track header', 'wp-powersuite' ); ?></strong>
							</label>
							<p class="description wpps-field-indent">
								<?php esc_html_e( 'Skips loading GA4 entirely when the browser sends a DNT signal.', 'wp-powersuite' ); ?>
							</p>
						</fieldset>
					</td>
				</tr>
			</tbody>
		</table>

		<h3 class="wpps-settings-section-title"><?php esc_html_e( 'Status', 'wp-powersuite' ); ?></h3>
		<table class="form-table" role="presentation">
			<tbody>
				<tr>
					<th scope="row"><?php esc_html_e( 'Current Environment', 'wp-powersuite' ); ?></th>
					<td>
						<strong><?php echo esc_html( ucfirst( $environment ) ); ?></strong>
						<?php if ( $tracking_disabled ) : ?>
							<span class="wpps-status-badge wpps-status-badge--warning">
								<?php esc_html_e( 'Tracking disabled', 'wp-powersuite' ); ?>
							</span>
						<?php endif; ?>
						<p class="description">
							<?php esc_html_e( 'Set WP_ENVIRONMENT_TYPE in wp-config.php for reliable environment detection, e.g. define(\'WP_ENVIRONMENT_TYPE\', \'local\');', 'wp-powersuite' ); ?>
						</p>
					</td>
				</tr>
				<tr>
					<th scope="row"><?php esc_html_e( 'Tracking Status', 'wp-powersuite' ); ?></th>
					<td>
						<?php if ( $ga4_valid ) : ?>
							<span class="wpps-status-badge wpps-status-badge--success">
								<?php esc_html_e( 'Configured', 'wp-powersuite' ); ?>
							</span>
							<?php if ( $would_track ) : ?>
								<span class="wpps-status-badge wpps-status-badge--success">
									<?php esc_html_e( 'Active on production frontend', 'wp-powersuite' ); ?>
								</span>
							<?php else : ?>
								<span class="wpps-status-badge wpps-status-badge--warning">
									<?php esc_html_e( 'Configured but suppressed by environment/settings', 'wp-powersuite' ); ?>
								</span>
							<?php endif; ?>
						<?php else : ?>
							<span class="wpps-status-badge wpps-status-badge--warning">
								<?php esc_html_e( 'Not configured', 'wp-powersuite' ); ?>
							</span>
							<?php if ( $ga4_id !== '' ) : ?>
								<p class="description wpps-status-note">
									<?php esc_html_e( 'Invalid format. Measurement ID must match G-XXXXXXXXXX (10 characters after G-).', 'wp-powersuite' ); ?>
								</p>
							<?php endif; ?>
						<?php endif; ?>
					</td>
				</tr>
				<?php if ( $duplicate_sources !== [] ) : ?>
				<tr>
					<th scope="row"><?php esc_html_e( 'Duplicate Tracking', 'wp-powersuite' ); ?></th>
					<td>
						<span class="wpps-status-badge wpps-status-badge--warning">
							<?php esc_html_e( 'Possible duplicate detected', 'wp-powersuite' ); ?>
						</span>
						<p class="description wpps-status-note">
							<?php
							echo esc_html(
								sprintf(
									/* translators: %s: comma-separated module names */
									__( 'GA4/gtag code also appears in: %s. This module will auto-skip injection to avoid double pageviews.', 'wp-powersuite' ),
									implode( ', ', $duplicate_sources )
								)
							);
							?>
						</p>
					</td>
				</tr>
				<?php endif; ?>
			</tbody>
		</table>

		<div class="notice notice-warning inline wpps-settings-notice">
			<p>
				<strong><?php esc_html_e( 'Privacy notice:', 'wp-powersuite' ); ?></strong>
				<?php esc_html_e( 'GA4 may still require consent in regulated regions. Use a consent banner/CMP and hook apply_filters(\'wpps_allow_analytics\', true) to block tracking until consent is granted. When Consent Mode is enabled, the tag loads with denied defaults and only sends pageviews after the filter allows it.', 'wp-powersuite' ); ?>
			</p>
		</div>

		<div class="notice notice-info inline wpps-settings-notice">
			<p>
				<strong><?php esc_html_e( 'Compatibility notes:', 'wp-powersuite' ); ?></strong>
				<?php esc_html_e( 'If Advanced Security Headers CSP is enabled, allow https://www.googletagmanager.com in script-src and connect-src. Avoid adding the same GA4 snippet in Header & Footer Code or other analytics plugins.', 'wp-powersuite' ); ?>
			</p>
		</div>
	</form>
</div>

<style>
.wpps-settings-section-title { margin-top: 30px; }
.wpps-field-indent { margin-left: 25px; margin-top: 5px; }
.wpps-field-block { display: block; margin-top: 15px; }
.wpps-role-checkboxes { display: grid; grid-template-columns: repeat(auto-fill, minmax(180px, 1fr)); gap: 8px 16px; max-width: 720px; }
.wpps-role-checkboxes__item { display: flex; align-items: center; gap: 8px; margin: 0; }
.wpps-status-badge { margin-left: 10px; font-weight: 600; }
.wpps-status-badge--success { color: #00a32a; }
.wpps-status-badge--warning { color: #d63638; }
.wpps-status-note { margin-top: 8px; }
.wpps-settings-notice { margin-top: 20px; }
</style>
