<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

use WP_PowerSuite\Core\OptionStoreModuleSettingsRepository;
use WP_PowerSuite\OAuth\Helpers\OAuthSettingsHelper;
use WP_PowerSuite\OAuth\Admin\SettingsUiHelper;
use WP_PowerSuite\OAuth\UI\ButtonStyleHelper;

if ( ! isset( $module_id ) || empty( $module_id ) ) {
	$module_id = 'google-sign-in';
}

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

$client_id                   = trim( $settings['client_id'] ?? '' );
$client_secret_stored        = trim( $settings['client_secret'] ?? '' );
$client_secret               = OAuthSettingsHelper::secretFieldValue( $client_secret_stored );
$auto_register               = ! empty( $settings['auto_register'] );
$bypass_registration_setting = ! empty( $settings['bypass_registration_setting'] );
$default_role                = in_array( $settings['default_role'] ?? 'subscriber', [ 'subscriber', 'contributor', 'author', 'editor' ], true ) ? ( $settings['default_role'] ?? 'subscriber' ) : 'subscriber';
$redirect_after_login        = trim( $settings['redirect_after_login'] ?? '' );
$store_avatar_url            = ! array_key_exists( 'store_avatar_url', $settings ) || ! empty( $settings['store_avatar_url'] );
$woo_login                   = ! empty( $settings['woo_login'] );
$button_style                = ButtonStyleHelper::sanitize( (string) ( $settings['button_style'] ?? 'default' ) );
$button_display              = ButtonStyleHelper::sanitizeDisplay( (string) ( $settings['button_display'] ?? 'label' ) );
$button_label_inline         = ButtonStyleHelper::sanitizeLabelInline( $settings['button_label_inline'] ?? false );

$public_callback = add_query_arg( \WP_PowerSuite\OAuth\Helpers\UrlHelper::AUTH_QUERY_PARAM, 'google', home_url( '/' ) );
$legacy_callback = add_query_arg( 'action', 'wpps_google_signin_callback', admin_url( 'admin-ajax.php' ) );
$uid             = preg_replace( '/[^a-z0-9_-]/i', '', $module_id );
?>

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

		<?php SettingsUiHelper::renderHttpsNotice(); ?>

		<div class="wpps-ts-accordions">
			<div class="wpps-ts-accordion is-open">
				<button type="button" class="wpps-ts-accordion-header" id="<?php echo esc_attr( $uid ); ?>_acc_head_credentials" aria-expanded="true" aria-controls="<?php echo esc_attr( $uid ); ?>_acc_body_credentials">
					<span class="wpps-ts-accordion-title"><?php esc_html_e( 'Google OAuth Credentials', 'wp-powersuite' ); ?></span>
					<span class="dashicons dashicons-arrow-down-alt2 wpps-ts-accordion-chevron" aria-hidden="true"></span>
				</button>
				<div class="wpps-ts-accordion-body" id="<?php echo esc_attr( $uid ); ?>_acc_body_credentials" role="region" aria-labelledby="<?php echo esc_attr( $uid ); ?>_acc_head_credentials">
					<p class="description" style="margin-top:0;">
						<?php esc_html_e( 'Create OAuth 2.0 credentials in the Google Cloud Console. Add the redirect URI below to your OAuth client\'s authorized redirect URIs.', 'wp-powersuite' ); ?>
					</p>

					<table class="form-table" role="presentation">
						<tbody>
							<tr>
								<th scope="row">
									<label for="<?php echo esc_attr( $module_id ); ?>_client_id">
										<?php esc_html_e( 'Client ID', 'wp-powersuite' ); ?>
									</label>
								</th>
								<td>
									<input
										type="text"
										id="<?php echo esc_attr( $module_id ); ?>_client_id"
										name="<?php echo esc_attr( $module_id ); ?>[client_id]"
										value="<?php echo esc_attr( $client_id ); ?>"
										class="regular-text wp-powersuite-advanced-setting"
										data-setting-key="client_id"
										placeholder="<?php esc_attr_e( 'xxxxx.apps.googleusercontent.com', 'wp-powersuite' ); ?>"
									/>
									<p class="description">
										<?php esc_html_e( 'OAuth 2.0 Client ID from Google Cloud Console.', 'wp-powersuite' ); ?>
										<a href="https://console.cloud.google.com/apis/credentials" target="_blank" rel="noopener noreferrer"><?php esc_html_e( 'Get credentials', 'wp-powersuite' ); ?></a>
									</p>
								</td>
							</tr>
							<tr>
								<th scope="row">
									<label for="<?php echo esc_attr( $module_id ); ?>_client_secret">
										<?php esc_html_e( 'Client Secret', 'wp-powersuite' ); ?>
									</label>
								</th>
								<td>
									<input
										type="password"
										id="<?php echo esc_attr( $module_id ); ?>_client_secret"
										name="<?php echo esc_attr( $module_id ); ?>[client_secret]"
										value="<?php echo esc_attr( $client_secret ); ?>"
										class="regular-text wp-powersuite-advanced-setting"
										data-setting-key="client_secret"
										placeholder="<?php esc_attr_e( 'GOCSPX-xxxxx', 'wp-powersuite' ); ?>"
										autocomplete="off"
									/>
									<p class="description">
										<?php esc_html_e( 'OAuth 2.0 Client Secret. Keep this private. Leave unchanged to keep the saved secret.', 'wp-powersuite' ); ?>
									</p>
								</td>
							</tr>
							<tr>
								<th scope="row">
									<label><?php esc_html_e( 'Authorized Redirect URI (recommended)', 'wp-powersuite' ); ?></label>
								</th>
								<td>
									<code style="display:block;padding:8px;background:#f0f0f1;word-break:break-all;"><?php echo esc_html( $public_callback ); ?></code>
									<p class="description">
										<?php esc_html_e( 'Add this exact URL to Google Cloud Console → OAuth client → Authorized redirect URIs.', 'wp-powersuite' ); ?>
									</p>
									<p style="margin-top:10px;">
										<button type="button" class="button button-secondary" id="wpps-copy-google-callback" data-url="<?php echo esc_attr( $public_callback ); ?>"><?php esc_html_e( 'Copy URL', 'wp-powersuite' ); ?></button>
									</p>
								</td>
							</tr>
							<tr>
								<th scope="row">
									<label><?php esc_html_e( 'Legacy redirect (optional)', 'wp-powersuite' ); ?></label>
								</th>
								<td>
									<code style="display:block;padding:8px;background:#f6f6f6;word-break:break-all;"><?php echo esc_html( $legacy_callback ); ?></code>
									<p class="description">
										<?php esc_html_e( 'If you set up Google before this version, you can keep this URL in the console too — both are accepted.', 'wp-powersuite' ); ?>
									</p>
								</td>
							</tr>
							<tr>
								<th scope="row">
									<label for="<?php echo esc_attr( $module_id ); ?>_button_style">
										<?php esc_html_e( 'Button style', 'wp-powersuite' ); ?>
									</label>
								</th>
								<td>
									<select
										id="<?php echo esc_attr( $module_id ); ?>_button_style"
										name="<?php echo esc_attr( $module_id ); ?>[button_style]"
										class="wp-powersuite-advanced-setting"
										data-setting-key="button_style"
									>
										<option value="default" <?php selected( $button_style, 'default' ); ?>><?php esc_html_e( 'Filled', 'wp-powersuite' ); ?></option>
										<option value="outline" <?php selected( $button_style, 'outline' ); ?>><?php esc_html_e( 'Outline', 'wp-powersuite' ); ?></option>
										<option value="minimal" <?php selected( $button_style, 'minimal' ); ?>><?php esc_html_e( 'Minimal', 'wp-powersuite' ); ?></option>
									</select>
									<p class="description">
										<?php esc_html_e( 'Icon-only: inline (auto). Text+icon: optional “Inline row” below, or use shortcode width/align.', 'wp-powersuite' ); ?>
									</p>
								</td>
							</tr>
							<tr>
								<th scope="row">
									<label for="<?php echo esc_attr( $module_id ); ?>_button_display"><?php esc_html_e( 'Label & icon', 'wp-powersuite' ); ?></label>
								</th>
								<td>
									<select id="<?php echo esc_attr( $module_id ); ?>_button_display" name="<?php echo esc_attr( $module_id ); ?>[button_display]" class="wp-powersuite-advanced-setting" data-setting-key="button_display">
										<option value="label" <?php selected( $button_display, 'label' ); ?>><?php esc_html_e( 'Text and icon', 'wp-powersuite' ); ?></option>
										<option value="icon" <?php selected( $button_display, 'icon' ); ?>><?php esc_html_e( 'Icon only', 'wp-powersuite' ); ?></option>
									</select>
								</td>
							</tr>
							<tr
								id="<?php echo esc_attr( $module_id ); ?>_label_inline_row"
								style="<?php echo ( $button_display === 'label' ) ? '' : 'display:none;'; ?>"
							>
								<th scope="row">
									<label for="<?php echo esc_attr( $module_id ); ?>_button_label_inline"><?php esc_html_e( 'Inline row (text and icon)', 'wp-powersuite' ); ?></label>
								</th>
								<td>
									<label>
										<input
											type="checkbox"
											id="<?php echo esc_attr( $module_id ); ?>_button_label_inline"
											name="<?php echo esc_attr( $module_id ); ?>[button_label_inline]"
											value="1"
											<?php checked( $button_label_inline ); ?>
											class="wp-powersuite-advanced-setting"
											data-setting-key="button_label_inline"
										/>
										<?php esc_html_e( 'Use auto width so multiple labeled buttons can sit in one row', 'wp-powersuite' ); ?>
									</label>
								</td>
							</tr>
						</tbody>
					</table>

					<div class="wp-powersuite-info-box" style="background: #fff8e5; border-left: 4px solid #dba617; padding: 12px; margin: 20px 0 0;">
						<p style="margin: 0 0 8px 0;">
							<strong><?php esc_html_e( 'Setup Steps', 'wp-powersuite' ); ?></strong>
						</p>
						<ol style="margin: 0; padding-left: 20px;">
							<li><?php esc_html_e( 'Go to Google Cloud Console → APIs & Services → Credentials', 'wp-powersuite' ); ?></li>
							<li><?php esc_html_e( 'Create OAuth 2.0 Client ID (Web application type)', 'wp-powersuite' ); ?></li>
							<li><?php esc_html_e( 'Add the Authorized Redirect URI shown above', 'wp-powersuite' ); ?></li>
							<li><?php esc_html_e( 'No additional APIs required—user info uses standard OAuth scopes', 'wp-powersuite' ); ?></li>
							<li><?php esc_html_e( 'Copy Client ID and Client Secret into the fields above', 'wp-powersuite' ); ?></li>
						</ol>
					</div>
				</div>
			</div>

			<div class="wpps-ts-accordion">
				<button type="button" class="wpps-ts-accordion-header" id="<?php echo esc_attr( $uid ); ?>_acc_head_registration" aria-expanded="false" aria-controls="<?php echo esc_attr( $uid ); ?>_acc_body_registration">
					<span class="wpps-ts-accordion-title"><?php esc_html_e( 'Registration & Users', 'wp-powersuite' ); ?></span>
					<span class="dashicons dashicons-arrow-down-alt2 wpps-ts-accordion-chevron" aria-hidden="true"></span>
				</button>
				<div class="wpps-ts-accordion-body" id="<?php echo esc_attr( $uid ); ?>_acc_body_registration" role="region" aria-labelledby="<?php echo esc_attr( $uid ); ?>_acc_head_registration">
					<table class="form-table" role="presentation">
						<tbody>
							<tr>
								<th scope="row">
									<label for="<?php echo esc_attr( $module_id ); ?>_auto_register">
										<?php esc_html_e( 'Auto-register New Users', 'wp-powersuite' ); ?>
									</label>
								</th>
								<td>
									<label>
										<input
											type="checkbox"
											id="<?php echo esc_attr( $module_id ); ?>_auto_register"
											name="<?php echo esc_attr( $module_id ); ?>[auto_register]"
											value="1"
											<?php checked( $auto_register ); ?>
											class="wp-powersuite-advanced-setting"
											data-setting-key="auto_register"
										/>
										<?php esc_html_e( 'Create WordPress accounts for new Google sign-ins', 'wp-powersuite' ); ?>
									</label>
									<p class="description">
										<?php esc_html_e( 'If disabled, only existing users (matched by email) can sign in with Google.', 'wp-powersuite' ); ?>
									</p>
								</td>
							</tr>
							<tr class="wpps-google-signin-auto-register-options" style="<?php echo $auto_register ? '' : 'display:none;'; ?>">
								<th scope="row">
									<label for="<?php echo esc_attr( $module_id ); ?>_bypass_registration_setting">
										<?php esc_html_e( 'Bypass "Anyone can register"', 'wp-powersuite' ); ?>
									</label>
								</th>
								<td>
									<label>
										<input
											type="checkbox"
											id="<?php echo esc_attr( $module_id ); ?>_bypass_registration_setting"
											name="<?php echo esc_attr( $module_id ); ?>[bypass_registration_setting]"
											value="1"
											<?php checked( $bypass_registration_setting ); ?>
											class="wp-powersuite-advanced-setting"
											data-setting-key="bypass_registration_setting"
										/>
										<?php esc_html_e( 'Allow Google sign-in registration even when "Anyone can register" is off', 'wp-powersuite' ); ?>
									</label>
								</td>
							</tr>
							<tr class="wpps-google-signin-auto-register-options" style="<?php echo $auto_register ? '' : 'display:none;'; ?>">
								<th scope="row">
									<label for="<?php echo esc_attr( $module_id ); ?>_default_role">
										<?php esc_html_e( 'Default Role for New Users', 'wp-powersuite' ); ?>
									</label>
								</th>
								<td>
									<select
										id="<?php echo esc_attr( $module_id ); ?>_default_role"
										name="<?php echo esc_attr( $module_id ); ?>[default_role]"
										class="wp-powersuite-advanced-setting"
										data-setting-key="default_role"
									>
										<option value="subscriber" <?php selected( $default_role, 'subscriber' ); ?>><?php esc_html_e( 'Subscriber', 'wp-powersuite' ); ?></option>
										<option value="contributor" <?php selected( $default_role, 'contributor' ); ?>><?php esc_html_e( 'Contributor', 'wp-powersuite' ); ?></option>
										<option value="author" <?php selected( $default_role, 'author' ); ?>><?php esc_html_e( 'Author', 'wp-powersuite' ); ?></option>
										<option value="editor" <?php selected( $default_role, 'editor' ); ?>><?php esc_html_e( 'Editor', 'wp-powersuite' ); ?></option>
									</select>
								</td>
							</tr>
							<tr>
								<th scope="row">
									<label for="<?php echo esc_attr( $module_id ); ?>_store_avatar_url">
										<?php esc_html_e( 'Store Google Avatar', 'wp-powersuite' ); ?>
									</label>
								</th>
								<td>
									<label>
										<input
											type="checkbox"
											id="<?php echo esc_attr( $module_id ); ?>_store_avatar_url"
											name="<?php echo esc_attr( $module_id ); ?>[store_avatar_url]"
											value="1"
											<?php checked( $store_avatar_url ); ?>
											class="wp-powersuite-advanced-setting"
											data-setting-key="store_avatar_url"
										/>
										<?php esc_html_e( 'Save Google profile picture URL in user meta (wpps_google_avatar)', 'wp-powersuite' ); ?>
									</label>
									<p class="description">
										<?php esc_html_e( 'When enabled, Google avatars can display via get_avatar() and compatible avatar plugins.', 'wp-powersuite' ); ?>
									</p>
								</td>
							</tr>
							<tr>
								<th scope="row">
									<label for="<?php echo esc_attr( $module_id ); ?>_redirect_after_login">
										<?php esc_html_e( 'Redirect After Login', 'wp-powersuite' ); ?>
									</label>
								</th>
								<td>
									<input
										type="url"
										id="<?php echo esc_attr( $module_id ); ?>_redirect_after_login"
										name="<?php echo esc_attr( $module_id ); ?>[redirect_after_login]"
										value="<?php echo esc_attr( $redirect_after_login ); ?>"
										class="regular-text wp-powersuite-advanced-setting"
										data-setting-key="redirect_after_login"
										placeholder="<?php esc_attr_e( 'Leave blank for site homepage', 'wp-powersuite' ); ?>"
									/>
									<p class="description">
										<?php esc_html_e( 'Where to send users after sign-in. Blank = site homepage.', 'wp-powersuite' ); ?>
									</p>
								</td>
							</tr>
							<?php if ( class_exists( 'WooCommerce' ) ) : ?>
							<tr>
								<th scope="row">
									<label for="<?php echo esc_attr( $module_id ); ?>_woo_login">
										<?php esc_html_e( 'WooCommerce', 'wp-powersuite' ); ?>
									</label>
								</th>
								<td>
									<label>
										<input
											type="checkbox"
											id="<?php echo esc_attr( $module_id ); ?>_woo_login"
											name="<?php echo esc_attr( $module_id ); ?>[woo_login]"
											value="1"
											<?php checked( $woo_login ); ?>
											class="wp-powersuite-advanced-setting"
											data-setting-key="woo_login"
										/>
										<?php esc_html_e( 'Show Sign in with Google on WooCommerce login and registration forms', 'wp-powersuite' ); ?>
									</label>
								</td>
							</tr>
							<?php endif; ?>
						</tbody>
					</table>
				</div>
			</div>

			<?php
			if ( class_exists( \WP_PowerSuite\OAuth\Admin\LinkingPolicySection::class ) ) {
				\WP_PowerSuite\OAuth\Admin\LinkingPolicySection::render(
					[
						'as_accordion' => true,
						'uid'          => $uid,
					]
				);
			}
			?>
		</div>

		<div class="wp-powersuite-info-box" style="background: #f0f6fc; border-left: 4px solid #2271b1; padding: 12px; margin: 20px 0 0;">
			<p style="margin: 0 0 8px 0;">
				<strong><?php esc_html_e( 'Shortcode', 'wp-powersuite' ); ?></strong>
			</p>
			<p style="margin: 0 0 8px 0;">
				<code>[social_login providers="google" style="outline"]</code> — <?php esc_html_e( 'unified (multiple providers in one place)', 'wp-powersuite' ); ?>
			</p>
			<p style="margin: 0 0 8px 0;">
				<code>[google_sign_in]</code>
			</p>
			<p style="margin: 0 0 8px 0;">
				<?php esc_html_e( 'Optional: redirect, label, style (default, outline, minimal).', 'wp-powersuite' ); ?>
			</p>
			<p style="margin: 0;">
				<code>[google_sign_in style="outline"]</code>
			</p>
		</div>
</form>
</div>

<script>
(function() {
	var cb = document.getElementById('<?php echo esc_js( $module_id ); ?>_auto_register');
	var rows = document.querySelectorAll('.wpps-google-signin-auto-register-options');
	if (cb && rows.length) {
		function toggle() {
			rows.forEach(function(r) { r.style.display = cb.checked ? '' : 'none'; });
		}
		cb.addEventListener('change', toggle);
		toggle();
	}
	var copy = document.getElementById('wpps-copy-google-callback');
	if (copy) {
		copy.addEventListener('click', function() {
			var u = copy.getAttribute('data-url');
			if (!u) return;
			if (navigator.clipboard && navigator.clipboard.writeText) {
				navigator.clipboard.writeText(u).then(function() { copy.textContent = '<?php echo esc_js( __( 'Copied!', 'wp-powersuite' ) ); ?>'; setTimeout(function() { copy.textContent = '<?php echo esc_js( __( 'Copy URL', 'wp-powersuite' ) ); ?>'; }, 2000); });
			}
		});
	}
	var slDisp = document.getElementById('<?php echo esc_js( $module_id ); ?>_button_display');
	var slRow = document.getElementById('<?php echo esc_js( $module_id ); ?>_label_inline_row');
	var slChk = document.getElementById('<?php echo esc_js( $module_id ); ?>_button_label_inline');
	if ( slDisp && slRow ) {
		function wppsSlToggleLabelInline() {
			var show = slDisp.value === 'label';
			slRow.style.display = show ? '' : 'none';
			if ( ! show && slChk ) { slChk.checked = false; }
		}
		slDisp.addEventListener('change', wppsSlToggleLabelInline);
		wppsSlToggleLabelInline();
	}
})();
</script>
