<?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 ?? 'github-sign-in' ); ?>">
		<div class="notice notice-warning inline" style="margin:0;">
			<p>
				<?php esc_html_e( 'GitHub Sign-in requires an active license. Activate your license to configure GitHub 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 = 'github-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            = ! empty( $settings['store_avatar_url'] );
$woo_login                   = ! empty( $settings['woo_login'] );
$allow_signup                = ! isset( $settings['allow_signup'] ) || ! empty( $settings['allow_signup'] );
$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, 'github', home_url( '/' ) );
$legacy_callback = add_query_arg( 'action', 'wpps_github_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( 'GitHub 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 an OAuth App in GitHub Developer Settings. Add the redirect URI below to your OAuth app\'s callback URL.', '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( 'Ov23li...', 'wp-powersuite' ); ?>"
						/>
						<p class="description">
							<?php esc_html_e( 'OAuth App Client ID from GitHub.', 'wp-powersuite' ); ?>
							<a href="https://github.com/settings/developers" 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( 'ghp_xxxxx or secret', 'wp-powersuite' ); ?>"
							autocomplete="off"
						/>
						<p class="description">
							<?php esc_html_e( 'OAuth App 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( 'Authorization callback URL (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 in GitHub → OAuth Apps → Authorization callback URL.', 'wp-powersuite' ); ?>
						</p>
						<p style="margin-top:10px;">
							<button type="button" class="button button-secondary" id="wpps-copy-github-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 callback (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( 'Previously used admin-ajax URL; still supported if listed in your GitHub app.', 'wp-powersuite' ); ?>
						</p>
					</td>
				</tr>
				<tr>
					<th scope="row">
						<label for="<?php echo esc_attr( $module_id ); ?>_allow_signup">
							<?php esc_html_e( 'Allow GitHub Sign-up', 'wp-powersuite' ); ?>
						</label>
					</th>
					<td>
						<label>
							<input
								type="checkbox"
								id="<?php echo esc_attr( $module_id ); ?>_allow_signup"
								name="<?php echo esc_attr( $module_id ); ?>[allow_signup]"
								value="1"
								<?php checked( $allow_signup ); ?>
								class="wp-powersuite-advanced-setting"
								data-setting-key="allow_signup"
							/>
							<?php esc_html_e( 'Show option to create a new GitHub account during OAuth flow', 'wp-powersuite' ); ?>
						</label>
						<p class="description">
							<?php esc_html_e( 'If disabled, only users with existing GitHub accounts can sign in.', '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 GitHub → Settings → Developer settings → OAuth Apps', 'wp-powersuite' ); ?></li>
							<li><?php esc_html_e( 'Click "New OAuth App"', 'wp-powersuite' ); ?></li>
							<li><?php esc_html_e( 'Set Application name and Homepage URL', 'wp-powersuite' ); ?></li>
							<li><?php esc_html_e( 'Add the Authorization callback URL shown above', 'wp-powersuite' ); ?></li>
							<li><?php esc_html_e( 'Copy Client ID and generate a Client Secret', 'wp-powersuite' ); ?></li>
							<li><?php esc_html_e( 'Paste credentials 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 GitHub sign-ins', 'wp-powersuite' ); ?>
						</label>
						<p class="description">
							<?php esc_html_e( 'If disabled, only existing users (matched by email) can sign in with GitHub. Note: GitHub users must have a verified email for registration.', 'wp-powersuite' ); ?>
						</p>
					</td>
				</tr>
				<tr class="wpps-github-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 GitHub sign-in registration even when "Anyone can register" is off', 'wp-powersuite' ); ?>
						</label>
					</td>
				</tr>
				<tr class="wpps-github-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 GitHub 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 GitHub profile picture URL in user meta (wpps_github_avatar)', 'wp-powersuite' ); ?>
						</label>
						<p class="description">
							<?php esc_html_e( 'Use with Local User Avatar or similar plugins to display GitHub avatars.', '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 GitHub 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="github" style="outline"]</code>
			</p>
			<p style="margin: 0 0 8px 0;">
				<code>[github_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>[github_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-github-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-github-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 ghd = document.getElementById('<?php echo esc_js( $module_id ); ?>_button_display');
	var ghr = document.getElementById('<?php echo esc_js( $module_id ); ?>_label_inline_row');
	var ghc = document.getElementById('<?php echo esc_js( $module_id ); ?>_button_label_inline');
	if (ghd && ghr) {
		function ght() {
			var show = ghd.value === 'label';
			ghr.style.display = show ? '' : 'none';
			if (!show && ghc) { ghc.checked = false; }
		}
		ghd.addEventListener('change', ght);
		ght();
	}
})();
</script>
