<?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.', '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 = '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', 'wp-powersuite' ),
	600  => __( '10 minutes', 'wp-powersuite' ),
	900  => __( '15 minutes', 'wp-powersuite' ),
	1200 => __( '20 minutes', 'wp-powersuite' ),
	1800 => __( '30 minutes', 'wp-powersuite' ),
	3600 => __( '60 minutes', 'wp-powersuite' ),
];
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', 'wp-powersuite' ),
	5  => __( '5 attempts', 'wp-powersuite' ),
	8  => __( '8 attempts', 'wp-powersuite' ),
	10 => __( '10 attempts', 'wp-powersuite' ),
];
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', 'wp-powersuite' ),
	1  => __( '1 day', 'wp-powersuite' ),
	3  => __( '3 days', 'wp-powersuite' ),
	7  => __( '7 days', 'wp-powersuite' ),
	14 => __( '14 days', 'wp-powersuite' ),
	30 => __( '30 days', 'wp-powersuite' ),
	60 => __( '60 days', 'wp-powersuite' ),
	90 => __( '90 days', 'wp-powersuite' ),
];
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', 'wp-powersuite' ),
	7  => __( '7 days', 'wp-powersuite' ),
	14 => __( '14 days', 'wp-powersuite' ),
	30 => __( '30 days', 'wp-powersuite' ),
	60 => __( '60 days', 'wp-powersuite' ),
	90 => __( '90 days', 'wp-powersuite' ),
];
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" 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" style="margin-top:0;">
						<?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.', 'wp-powersuite' ); ?>
					</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', 'wp-powersuite' ); ?></label>
						<?php
						wpps_render_modal_settings_tip(
							__( 'Help: enforced roles', 'wp-powersuite' ),
							__( 'Users with these roles will be required to enter a verification code after logging in with their password.', 'wp-powersuite' )
						);
						?>
					</th>
					<td>
						<?php if ( empty( $all_roles ) ) : ?>
							<p class="description"><?php esc_html_e( 'No roles found.', 'wp-powersuite' ); ?></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...', 'wp-powersuite' ) ); ?>"
								data-label-single="<?php echo esc_attr( __( '1 selected', 'wp-powersuite' ) ); ?>"
								data-label-multi="<?php echo esc_attr( __( '%d selected', 'wp-powersuite' ) ); ?>">
								<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...', 'wp-powersuite' ); ?></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...', 'wp-powersuite' ); ?>" 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', 'wp-powersuite' ); ?></button>
										<button type="button" class="wpps-ct-multiselect__action" data-action="clear"><?php esc_html_e( 'Clear', 'wp-powersuite' ); ?></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', 'wp-powersuite' ); ?></label>
						<?php
						wpps_render_modal_settings_tip(
							__( 'Help: 2FA methods', 'wp-powersuite' ),
							__( 'Choose which methods users can use. At least one must be enabled. Users choose their preferred method in their profile.', 'wp-powersuite' )
						);
						?>
					</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', 'wp-powersuite' ); ?>
							</label>
							<?php
							wpps_render_modal_settings_tip(
								__( 'Help: email code', 'wp-powersuite' ),
								__( 'Default for all users. Sends an 8-digit code to the user’s email.', 'wp-powersuite' )
							);
							?>
						</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', 'wp-powersuite' ); ?>
							</label>
							<?php
							wpps_render_modal_settings_tip(
								__( 'Help: authenticator app', 'wp-powersuite' ),
								__( 'TOTP apps (Google Authenticator, Authy, etc.). Users set up in their profile.', 'wp-powersuite' )
							);
							?>
						</p>
					</td>
				</tr>
				<tr>
					<th scope="row">
						<label for="wpps-2fa-email-ttl"><?php esc_html_e( 'Email code validity', 'wp-powersuite' ); ?></label>
						<?php
						wpps_render_modal_settings_tip(
							__( 'Help: email code validity', 'wp-powersuite' ),
							__( 'How long an emailed login code and the pending 2FA session remain valid (TOTP step uses the same timeout).', 'wp-powersuite' )
						);
						?>
					</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', 'wp-powersuite' ); ?></label>
						<?php
						wpps_render_modal_settings_tip(
							__( 'Help: wrong code limit', 'wp-powersuite' ),
							__( 'After this many incorrect codes for one sign-in attempt, the user must enter username and password again.', 'wp-powersuite' )
						);
						?>
					</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', 'wp-powersuite' ); ?></label>
						<?php
						wpps_render_modal_settings_tip(
							__( 'Help: grace period', 'wp-powersuite' ),
							__( '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.', 'wp-powersuite' )
						);
						?>
					</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', 'wp-powersuite' ); ?></label>
						<?php
						wpps_render_modal_settings_tip(
							__( 'Help: trusted browser', 'wp-powersuite' ),
							__( 'Optional: after completing the second factor, users can skip it on this browser until the cookie expires.', 'wp-powersuite' )
						);
						?>
					</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', 'wp-powersuite' ); ?>
						<?php
						wpps_render_modal_settings_tip(
							__( 'Help: REST and XML-RPC', 'wp-powersuite' ),
							__( '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.', 'wp-powersuite' )
						);
						?>
					</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.', 'wp-powersuite' ); ?>
							</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', 'wp-powersuite' ); ?>
						</label>
					</td>
				</tr>
			</tbody>
		</table>
</form>
</div>
