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

use WP_PowerSuite\Core\OptionStoreModuleSettingsRepository;

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 ?? 'two-factor-authentication' ); ?>">
		<div class="notice notice-warning inline" style="margin:0;">
			<p>
				<?php esc_html_e( 'Two-Factor Authentication requires an active license. Activate your license to configure 2FA.', 'wppowersuite-lite' ); ?>
				<a href="<?php echo esc_url( $license_page_url ); ?>"><?php esc_html_e( 'Activate license', 'wppowersuite-lite' ); ?></a>
			</p>
		</div>
	</div>
	<?php
	return;
}

if ( ! isset( $module_id ) || empty( $module_id ) ) {
	$module_id = 'two-factor-authentication';
}

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

$defaults = [
	'roles'                 => [],
	'enable_email'          => true,
	'enable_authenticator'  => true,
	'email_code_ttl'        => 1200,
	'max_verify_attempts'   => 5,
	'grace_period_days'     => 0,
	'trusted_device_days'   => 0,
	'restrict_api_login_to_app_passwords' => true,
];
$settings = array_merge( $defaults, $settings );

$app_passwords_module_enabled = OptionStoreModuleSettingsRepository::isModuleEnabled( 'disable-application-passwords' );
if ( $app_passwords_module_enabled ) {
	$settings['restrict_api_login_to_app_passwords'] = false;
}

$ttl       = isset( $settings['email_code_ttl'] ) ? absint( $settings['email_code_ttl'] ) : 1200;
$ttl_opts  = [
	300  => __( '5 minutes', 'wppowersuite-lite' ),
	600  => __( '10 minutes', 'wppowersuite-lite' ),
	900  => __( '15 minutes', 'wppowersuite-lite' ),
	1200 => __( '20 minutes', 'wppowersuite-lite' ),
	1800 => __( '30 minutes', 'wppowersuite-lite' ),
	3600 => __( '60 minutes', 'wppowersuite-lite' ),
];
if ( ! isset( $ttl_opts[ $ttl ] ) ) {
	$ttl = 1200;
}

$max_att   = isset( $settings['max_verify_attempts'] ) ? absint( $settings['max_verify_attempts'] ) : 5;
$att_opts  = [
	3  => __( '3 attempts', 'wppowersuite-lite' ),
	5  => __( '5 attempts', 'wppowersuite-lite' ),
	8  => __( '8 attempts', 'wppowersuite-lite' ),
	10 => __( '10 attempts', 'wppowersuite-lite' ),
];
if ( ! isset( $att_opts[ $max_att ] ) ) {
	$max_att = 5;
}

$grace_days = isset( $settings['grace_period_days'] ) ? absint( $settings['grace_period_days'] ) : 0;
$grace_opts = [
	0  => __( 'Off', 'wppowersuite-lite' ),
	1  => __( '1 day', 'wppowersuite-lite' ),
	3  => __( '3 days', 'wppowersuite-lite' ),
	7  => __( '7 days', 'wppowersuite-lite' ),
	14 => __( '14 days', 'wppowersuite-lite' ),
	30 => __( '30 days', 'wppowersuite-lite' ),
	60 => __( '60 days', 'wppowersuite-lite' ),
	90 => __( '90 days', 'wppowersuite-lite' ),
];
if ( ! isset( $grace_opts[ $grace_days ] ) ) {
	$grace_days = 0;
}

$trust_days = isset( $settings['trusted_device_days'] ) ? absint( $settings['trusted_device_days'] ) : 0;
$trust_opts = [
	0  => __( 'Off', 'wppowersuite-lite' ),
	7  => __( '7 days', 'wppowersuite-lite' ),
	14 => __( '14 days', 'wppowersuite-lite' ),
	30 => __( '30 days', 'wppowersuite-lite' ),
	60 => __( '60 days', 'wppowersuite-lite' ),
	90 => __( '90 days', 'wppowersuite-lite' ),
];
if ( ! isset( $trust_opts[ $trust_days ] ) ) {
	$trust_days = 0;
}

$selected_roles = $settings['roles'] ?? [];
if ( ! is_array( $selected_roles ) ) {
	$selected_roles = [];
}

$all_roles = wp_roles()->get_names();
?>

<div class="wp-powersuite-module-settings wpps-settings-panel wpps-settings-panel--compact-form wpps-2fa-settings" 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' ); ?>

		<p class="description wpps-module-settings-lead">
			<?php esc_html_e( 'Users with selected roles must complete a second step after entering their password: an email code and/or an authenticator app, depending on your settings and their profile.', 'wppowersuite-lite' ); ?>
		</p>

		<table class="form-table" role="presentation">
			<tbody>
				<tr>
					<th scope="row">
						<label><?php esc_html_e( 'Select roles to apply Two Factor Authentication to', 'wppowersuite-lite' ); ?></label>
						<?php
						wpps_render_modal_settings_tip(
							__( 'Help: enforced roles', 'wppowersuite-lite' ),
							__( 'Users with these roles will be required to enter a verification code after logging in with their password.', 'wppowersuite-lite' )
						);
						?>
					</th>
					<td>
						<?php if ( empty( $all_roles ) ) : ?>
							<p class="description"><?php esc_html_e( 'No roles found.', 'wppowersuite-lite' ); ?></p>
						<?php else : ?>
							<div class="wpps-ct-multiselect" id="<?php echo esc_attr( $module_id ); ?>_roles_ms"
								data-label-none="<?php echo esc_attr( __( 'Select roles...', 'wppowersuite-lite' ) ); ?>"
								data-label-single="<?php echo esc_attr( __( '1 selected', 'wppowersuite-lite' ) ); ?>"
								<?php /* translators: %d: number value. */ ?>
								data-label-multi="<?php echo esc_attr( __( '%d selected', 'wppowersuite-lite' ) ); ?>">
								<button type="button" class="wpps-ct-multiselect__trigger" aria-expanded="false" aria-haspopup="listbox" aria-controls="<?php echo esc_attr( $module_id ); ?>_roles_list">
									<span class="wpps-ct-multiselect__trigger-text"><?php esc_html_e( 'Select roles...', 'wppowersuite-lite' ); ?></span>
									<span class="dashicons dashicons-arrow-down-alt2 wpps-ct-multiselect__chevron"></span>
								</button>
								<div class="wpps-ct-multiselect__dropdown" id="<?php echo esc_attr( $module_id ); ?>_roles_list" role="listbox" hidden>
									<input type="text" class="wpps-ct-multiselect__search" placeholder="<?php esc_attr_e( 'Search roles...', 'wppowersuite-lite' ); ?>" autocomplete="off" />
									<div class="wpps-ct-multiselect__actions">
										<button type="button" class="wpps-ct-multiselect__action" data-action="select-all"><?php esc_html_e( 'Select all', 'wppowersuite-lite' ); ?></button>
										<button type="button" class="wpps-ct-multiselect__action" data-action="clear"><?php esc_html_e( 'Clear', 'wppowersuite-lite' ); ?></button>
									</div>
									<div class="wpps-ct-multiselect__options">
										<?php foreach ( $all_roles as $role_key => $role_label ) : ?>
											<?php $checked = in_array( $role_key, $selected_roles, true ); ?>
											<label class="wpps-ct-multiselect__option" data-slug="<?php echo esc_attr( $role_key ); ?>" data-label="<?php echo esc_attr( $role_label ); ?>">
												<input type="checkbox" name="roles[]" class="wp-powersuite-advanced-setting" data-setting-key="roles" value="<?php echo esc_attr( $role_key ); ?>" <?php checked( $checked ); ?> />
												<span class="wpps-ct-multiselect__option-label"><?php echo esc_html( $role_label ); ?></span>
												<span class="wpps-ct-multiselect__option-slug">(<?php echo esc_html( $role_key ); ?>)</span>
											</label>
										<?php endforeach; ?>
									</div>
								</div>
							</div>
						<?php endif; ?>
					</td>
				</tr>
				<tr>
					<th scope="row">
						<label><?php esc_html_e( '2FA methods', 'wppowersuite-lite' ); ?></label>
						<?php
						wpps_render_modal_settings_tip(
							__( 'Help: 2FA methods', 'wppowersuite-lite' ),
							__( 'Choose which methods users can use. At least one must be enabled. Users choose their preferred method in their profile.', 'wppowersuite-lite' )
						);
						?>
					</th>
					<td>
						<p>
							<input type="hidden" name="enable_email" value="0" />
							<label>
								<input type="checkbox" name="enable_email" class="wp-powersuite-advanced-setting" data-setting-key="enable_email" value="1" <?php checked( ! empty( $settings['enable_email'] ) ); ?> />
								<?php esc_html_e( 'Email code', 'wppowersuite-lite' ); ?>
							</label>
							<?php
							wpps_render_modal_settings_tip(
								__( 'Help: email code', 'wppowersuite-lite' ),
								__( 'Default for all users. Sends an 8-digit code to the user’s email.', 'wppowersuite-lite' )
							);
							?>
						</p>
						<p style="margin-top: 8px;">
							<input type="hidden" name="enable_authenticator" value="0" />
							<label>
								<input type="checkbox" name="enable_authenticator" class="wp-powersuite-advanced-setting" data-setting-key="enable_authenticator" value="1" <?php checked( ! empty( $settings['enable_authenticator'] ) ); ?> />
								<?php esc_html_e( 'Authenticator app', 'wppowersuite-lite' ); ?>
							</label>
							<?php
							wpps_render_modal_settings_tip(
								__( 'Help: authenticator app', 'wppowersuite-lite' ),
								__( 'TOTP apps (Google Authenticator, Authy, etc.). Users set up in their profile.', 'wppowersuite-lite' )
							);
							?>
						</p>
					</td>
				</tr>
				<tr>
					<th scope="row">
						<label for="wpps-2fa-email-ttl"><?php esc_html_e( 'Email code validity', 'wppowersuite-lite' ); ?></label>
						<?php
						wpps_render_modal_settings_tip(
							__( 'Help: email code validity', 'wppowersuite-lite' ),
							__( 'How long an emailed login code and the pending 2FA session remain valid (TOTP step uses the same timeout).', 'wppowersuite-lite' )
						);
						?>
					</th>
					<td>
						<select id="wpps-2fa-email-ttl" name="email_code_ttl" class="wp-powersuite-advanced-setting" data-setting-key="email_code_ttl">
							<?php foreach ( $ttl_opts as $sec => $label ) : ?>
								<option value="<?php echo esc_attr( (string) $sec ); ?>" <?php selected( $ttl, $sec ); ?>><?php echo esc_html( $label ); ?></option>
							<?php endforeach; ?>
						</select>
					</td>
				</tr>
				<tr>
					<th scope="row">
						<label for="wpps-2fa-max-att"><?php esc_html_e( 'Wrong code limit', 'wppowersuite-lite' ); ?></label>
						<?php
						wpps_render_modal_settings_tip(
							__( 'Help: wrong code limit', 'wppowersuite-lite' ),
							__( 'After this many incorrect codes for one sign-in attempt, the user must enter username and password again.', 'wppowersuite-lite' )
						);
						?>
					</th>
					<td>
						<select id="wpps-2fa-max-att" name="max_verify_attempts" class="wp-powersuite-advanced-setting" data-setting-key="max_verify_attempts">
							<?php foreach ( $att_opts as $n => $label ) : ?>
								<option value="<?php echo esc_attr( (string) $n ); ?>" <?php selected( $max_att, $n ); ?>><?php echo esc_html( $label ); ?></option>
							<?php endforeach; ?>
						</select>
					</td>
				</tr>
				<tr>
					<th scope="row">
						<label for="wpps-2fa-grace"><?php esc_html_e( 'Profile setup grace period', 'wppowersuite-lite' ); ?></label>
						<?php
						wpps_render_modal_settings_tip(
							__( 'Help: grace period', 'wppowersuite-lite' ),
							__( 'When the authenticator app method is enabled, affected users who have not yet confirmed their profile choices or set up an app must open their profile before the grace period ends, or they will be redirected there when accessing wp-admin. Off when not using authenticator.', 'wppowersuite-lite' )
						);
						?>
					</th>
					<td>
						<select id="wpps-2fa-grace" name="grace_period_days" class="wp-powersuite-advanced-setting" data-setting-key="grace_period_days">
							<?php foreach ( $grace_opts as $d => $label ) : ?>
								<option value="<?php echo esc_attr( (string) $d ); ?>" <?php selected( $grace_days, $d ); ?>><?php echo esc_html( $label ); ?></option>
							<?php endforeach; ?>
						</select>
					</td>
				</tr>
				<tr>
					<th scope="row">
						<label for="wpps-2fa-trust"><?php esc_html_e( 'Remember this browser', 'wppowersuite-lite' ); ?></label>
						<?php
						wpps_render_modal_settings_tip(
							__( 'Help: trusted browser', 'wppowersuite-lite' ),
							__( 'Optional: after completing the second factor, users can skip it on this browser until the cookie expires.', 'wppowersuite-lite' )
						);
						?>
					</th>
					<td>
						<select id="wpps-2fa-trust" name="trusted_device_days" class="wp-powersuite-advanced-setting" data-setting-key="trusted_device_days">
							<?php foreach ( $trust_opts as $d => $label ) : ?>
								<option value="<?php echo esc_attr( (string) $d ); ?>" <?php selected( $trust_days, $d ); ?>><?php echo esc_html( $label ); ?></option>
							<?php endforeach; ?>
						</select>
					</td>
				</tr>
				<tr>
					<th scope="row">
						<?php esc_html_e( 'REST / XML-RPC', 'wppowersuite-lite' ); ?>
						<?php
						wpps_render_modal_settings_tip(
							__( 'Help: REST and XML-RPC', 'wppowersuite-lite' ),
							__( 'Recommended. Matches WordPress Two-Factor behavior: users subject to this module should create an application password (Users → Profile) for API tools instead of using their account password.', 'wppowersuite-lite' )
						);
						?>
					</th>
					<td>
						<?php if ( $app_passwords_module_enabled ) : ?>
							<p class="description" style="color:#b32d2e;">
								<?php esc_html_e( 'Unavailable while Disable Application Passwords is enabled. Application passwords cannot be used for REST/XML-RPC on this site.', 'wppowersuite-lite' ); ?>
							</p>
						<?php endif; ?>
						<input type="hidden" name="restrict_api_login_to_app_passwords" value="0" />
						<label>
							<input type="checkbox" name="restrict_api_login_to_app_passwords" class="wp-powersuite-advanced-setting" data-setting-key="restrict_api_login_to_app_passwords" value="1" <?php checked( ! empty( $settings['restrict_api_login_to_app_passwords'] ) ); ?> <?php disabled( $app_passwords_module_enabled ); ?> />
							<?php esc_html_e( 'Require application passwords for REST API and XML-RPC when a user is in an enforced role', 'wppowersuite-lite' ); ?>
						</label>
					</td>
				</tr>
			</tbody>
		</table>
	</form>
</div>

