<?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 ( ! function_exists( 'wp_powersuite_is_license_valid' ) || ! wp_powersuite_is_license_valid() ) {
	$license_page_url = admin_url( 'admin.php?page=powersuite-license' );
	?>
	<div class="wp-powersuite-module-settings wpps-settings-panel" data-module-id="<?php echo esc_attr( $module_id ?? 'facebook-sign-in' ); ?>">
		<div class="notice notice-warning inline" style="margin:0;">
			<p>
				<?php esc_html_e( 'Facebook Sign In requires an active license. Activate your license to configure Facebook login.', 'wp-powersuite' ); ?>
				<a href="<?php echo esc_url( $license_page_url ); ?>"><?php esc_html_e( 'Activate license', 'wp-powersuite' ); ?></a>
			</p>
		</div>
	</div>
	<?php
	return;
}

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

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

$app_id              = trim( $settings['app_id'] ?? '' );
$app_secret_stored   = trim( $settings['app_secret'] ?? '' );
$app_secret          = OAuthSettingsHelper::secretFieldValue( $app_secret_stored );
$redirect_after      = trim( $settings['redirect_after_login'] ?? '' );
$allow_registration          = ! empty( $settings['allow_registration'] );
$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';
$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 );
$woo_login           = ! empty( $settings['woo_login'] );
$callback_url        = add_query_arg( \WP_PowerSuite\OAuth\Helpers\UrlHelper::AUTH_QUERY_PARAM, 'facebook', home_url( '/' ) );
$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( 'Facebook App 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 a Facebook App at developers.facebook.com, add the "Facebook Login" product, and configure the settings below.', 'wp-powersuite' ); ?>
					</p>

					<table class="form-table" role="presentation">
						<tbody>
							<tr>
								<th scope="row">
									<label for="<?php echo esc_attr( $module_id ); ?>_app_id">
										<?php esc_html_e( 'App ID', 'wp-powersuite' ); ?>
									</label>
								</th>
								<td>
									<input
										type="text"
										id="<?php echo esc_attr( $module_id ); ?>_app_id"
										name="<?php echo esc_attr( $module_id ); ?>[app_id]"
										value="<?php echo esc_attr( $app_id ); ?>"
										class="regular-text wp-powersuite-advanced-setting"
										data-setting-key="app_id"
										placeholder="1234567890123456"
									/>
									<p class="description">
										<?php esc_html_e( 'Your Facebook App ID from the app dashboard.', 'wp-powersuite' ); ?>
									</p>
								</td>
							</tr>
							<tr>
								<th scope="row">
									<label for="<?php echo esc_attr( $module_id ); ?>_app_secret">
										<?php esc_html_e( 'App Secret', 'wp-powersuite' ); ?>
									</label>
								</th>
								<td>
									<input
										type="password"
										id="<?php echo esc_attr( $module_id ); ?>_app_secret"
										name="<?php echo esc_attr( $module_id ); ?>[app_secret]"
										value="<?php echo esc_attr( $app_secret ); ?>"
										class="regular-text wp-powersuite-advanced-setting"
										data-setting-key="app_secret"
										placeholder="••••••••••••••••••••••••••••••••"
										autocomplete="off"
									/>
									<p class="description">
										<?php esc_html_e( 'Your Facebook App Secret. Keep this private. Leave unchanged to keep the saved secret.', '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: #f0f6fc; border-left: 4px solid #2271b1; padding: 12px; margin: 20px 0 0;">
						<p style="margin: 0 0 8px 0;">
							<strong><?php esc_html_e( 'Valid OAuth Redirect URIs', 'wp-powersuite' ); ?></strong>
						</p>
						<p style="margin: 0 0 8px 0;">
							<?php esc_html_e( 'Add this URL to your Facebook App → Facebook Login → Settings → Valid OAuth Redirect URIs:', 'wp-powersuite' ); ?>
						</p>
						<p style="margin: 0 0 8px 0;">
							<code style="word-break: break-all;"><?php echo esc_html( $callback_url ); ?></code>
						</p>
						<p style="margin: 8px 0 0 0;">
							<button type="button" class="button button-secondary wpps-copy-callback-url" data-url="<?php echo esc_attr( $callback_url ); ?>">
								<?php esc_html_e( 'Copy URL', 'wp-powersuite' ); ?>
							</button>
						</p>
					</div>

					<div class="wp-powersuite-info-box" style="background: #fcf0f1; border-left: 4px solid #d63638; padding: 12px; margin: 20px 0 0;">
						<p style="margin: 0 0 8px 0;">
							<strong><?php esc_html_e( 'Required Facebook App Permissions', 'wp-powersuite' ); ?></strong>
						</p>
						<p style="margin: 0;">
							<?php esc_html_e( 'Ensure your app requests "email" and "public_profile" permissions. These are included by default when adding the Facebook Login product.', 'wp-powersuite' ); ?>
						</p>
					</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 ); ?>_allow_registration">
										<?php esc_html_e( 'Allow New User Registration', 'wp-powersuite' ); ?>
									</label>
								</th>
								<td>
									<label>
										<input
											type="checkbox"
											id="<?php echo esc_attr( $module_id ); ?>_allow_registration"
											name="<?php echo esc_attr( $module_id ); ?>[allow_registration]"
											value="1"
											<?php checked( $allow_registration ); ?>
											class="wp-powersuite-advanced-setting"
											data-setting-key="allow_registration"
										/>
										<?php esc_html_e( 'Create new WordPress accounts for first-time Facebook sign-ins', 'wp-powersuite' ); ?>
									</label>
									<p class="description">
										<?php esc_html_e( 'If disabled, only existing users (matched by email) can sign in with Facebook.', 'wp-powersuite' ); ?>
									</p>
								</td>
							</tr>
							<tr class="wpps-facebook-signin-auto-register-options" style="<?php echo $allow_registration ? '' : '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 Facebook sign-in registration even when "Anyone can register" is off', 'wp-powersuite' ); ?>
									</label>
								</td>
							</tr>
							<tr class="wpps-facebook-signin-auto-register-options" style="<?php echo $allow_registration ? '' : '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 ); ?>_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 ); ?>"
										class="regular-text wp-powersuite-advanced-setting"
										data-setting-key="redirect_after_login"
										placeholder="<?php echo esc_attr( home_url( '/' ) ); ?>"
									/>
									<p class="description">
										<?php esc_html_e( 'Where to send users after successful login. Leave blank for 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 Facebook on WooCommerce login, registration, and checkout 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="facebook" type="button" style="outline"]</code>
			</p>
			<p style="margin: 0 0 8px 0;">
				<code>[facebook_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>[facebook_sign_in style="outline"]</code>
			</p>
		</div>
</form>
</div>

<script>
(function() {
	var cb = document.getElementById('<?php echo esc_js( $module_id ); ?>_allow_registration');
	var rows = document.querySelectorAll('.wpps-facebook-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();
	}
	document.addEventListener('click', function(e) {
		var btn = e.target.closest('.wpps-copy-callback-url');
		if (!btn) return;
		var url = btn.getAttribute('data-url');
		if (!url) return;
		if (navigator.clipboard && navigator.clipboard.writeText) {
			navigator.clipboard.writeText(url).then(function() {
				var orig = btn.textContent;
				btn.textContent = '<?php echo esc_js( __( 'Copied!', 'wp-powersuite' ) ); ?>';
				setTimeout(function() { btn.textContent = orig; }, 2000);
			});
		} else {
			var ta = document.createElement('textarea');
			ta.value = url;
			document.body.appendChild(ta);
			ta.select();
			document.execCommand('copy');
			document.body.removeChild(ta);
			var orig = btn.textContent;
			btn.textContent = '<?php echo esc_js( __( 'Copied!', 'wp-powersuite' ) ); ?>';
			setTimeout(function() { btn.textContent = orig; }, 2000);
		}
	});
	var d = document.getElementById('<?php echo esc_js( $module_id ); ?>_button_display');
	var row = document.getElementById('<?php echo esc_js( $module_id ); ?>_label_inline_row');
	var chk = document.getElementById('<?php echo esc_js( $module_id ); ?>_button_label_inline');
	if (d && row) {
		function t() {
			var on = d.value === 'label';
			row.style.display = on ? '' : 'none';
			if (!on && chk) { chk.checked = false; }
		}
		d.addEventListener('change', t);
		t();
	}
})();
</script>
