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

use LoginSessionManager\Includes\Session_Capabilities;
use LoginSessionManager\Module;
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 ?? 'login-session-manager' ); ?>">
		<div class="notice notice-warning inline" style="margin:0;">
			<p>
				<?php esc_html_e( 'Login Session Manager requires an active license. Activate your license to manage login sessions.', '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 = 'login-session-manager';
}

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

$defaults       = Module::getDefaultSettings();
$role_max       = is_array( $settings['role_max_sessions'] ?? null ) ? $settings['role_max_sessions'] : $defaults['role_max_sessions'];
$excluded_roles = is_array( $settings['excluded_roles'] ?? null ) ? $settings['excluded_roles'] : $defaults['excluded_roles'];
$limit_action   = (string) ( $settings['limit_exceeded_action'] ?? 'logout_oldest' );

$wp_roles  = wp_roles();
$all_roles = $wp_roles ? $wp_roles->roles : [];

$manager_active      = Session_Capabilities::is_manager_active( $settings );
$can_manage_sessions = $manager_active && user_can( get_current_user_id(), 'edit_users' );
$stats               = [
	'total_sessions'   => 0,
	'users_logged_in'  => 0,
	'sessions_by_role' => [],
];

$uid = preg_replace( '/[^a-z0-9_-]/i', '', $module_id );
?>

<div class="wp-powersuite-module-settings wpps-lsm-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' ); ?>

		<p class="description wpps-lsm-settings-lead">
			<?php esc_html_e( 'Stop unknown logins from staying active. Manage WordPress sessions from one dashboard.', 'wp-powersuite' ); ?>
		</p>

		<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_general" aria-expanded="true" aria-controls="<?php echo esc_attr( $uid ); ?>_acc_body_general">
					<span class="wpps-ts-accordion-title"><?php esc_html_e( 'General', '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_general" role="region" aria-labelledby="<?php echo esc_attr( $uid ); ?>_acc_head_general">
					<table class="form-table" role="presentation">
						<tbody>
							<tr>
								<th scope="row"><?php esc_html_e( 'Enable session manager', 'wp-powersuite' ); ?></th>
								<td>
									<label>
										<input type="checkbox" class="wp-powersuite-advanced-setting" data-setting-key="manager_enabled" name="<?php echo esc_attr( $module_id ); ?>[manager_enabled]" value="1" <?php checked( ! empty( $settings['manager_enabled'] ) ); ?> />
										<?php esc_html_e( 'Allow viewing and revoking active login sessions', 'wp-powersuite' ); ?>
									</label>
								</td>
							</tr>
							<tr>
								<th scope="row"><?php esc_html_e( 'User profile sessions', 'wp-powersuite' ); ?></th>
								<td>
									<label>
										<input type="checkbox" class="wp-powersuite-advanced-setting" data-setting-key="show_on_profile" name="<?php echo esc_attr( $module_id ); ?>[show_on_profile]" value="1" <?php checked( ! empty( $settings['show_on_profile'] ) ); ?> />
										<?php esc_html_e( 'Show active sessions on user profile screens', 'wp-powersuite' ); ?>
									</label>
								</td>
							</tr>
							<tr>
								<th scope="row"><?php esc_html_e( 'Users list column', 'wp-powersuite' ); ?></th>
								<td>
									<label>
										<input type="checkbox" class="wp-powersuite-advanced-setting" data-setting-key="show_users_column" name="<?php echo esc_attr( $module_id ); ?>[show_users_column]" value="1" <?php checked( ! empty( $settings['show_users_column'] ) ); ?> />
										<?php esc_html_e( 'Show active session count in the Users list', 'wp-powersuite' ); ?>
									</label>
								</td>
							</tr>
							<tr>
								<th scope="row"><?php esc_html_e( 'Admin bar link', 'wp-powersuite' ); ?></th>
								<td>
									<label>
										<input type="checkbox" class="wp-powersuite-advanced-setting" data-setting-key="show_admin_bar" name="<?php echo esc_attr( $module_id ); ?>[show_admin_bar]" value="1" <?php checked( ! empty( $settings['show_admin_bar'] ) ); ?> />
										<?php esc_html_e( 'Show active sessions in the admin bar when a user has more than one session', 'wp-powersuite' ); ?>
									</label>
								</td>
							</tr>
							<tr>
								<th scope="row"><?php esc_html_e( 'Privacy', 'wp-powersuite' ); ?></th>
								<td>
									<label style="display:block;margin-bottom:6px;">
										<input type="checkbox" class="wp-powersuite-advanced-setting" data-setting-key="hide_ip" name="<?php echo esc_attr( $module_id ); ?>[hide_ip]" value="1" <?php checked( ! empty( $settings['hide_ip'] ) ); ?> />
										<?php esc_html_e( 'Hide IP addresses in session lists', 'wp-powersuite' ); ?>
									</label>
									<label>
										<input type="checkbox" class="wp-powersuite-advanced-setting" data-setting-key="hide_user_agent" name="<?php echo esc_attr( $module_id ); ?>[hide_user_agent]" value="1" <?php checked( ! empty( $settings['hide_user_agent'] ) ); ?> />
										<?php esc_html_e( 'Omit raw user-agent strings from AJAX responses', 'wp-powersuite' ); ?>
									</label>
								</td>
							</tr>
						</tbody>
					</table>
				</div>
			</div>

			<?php if ( $can_manage_sessions ) : ?>
				<div class="wpps-ts-accordion" id="wpps-lsm-acc-sessions">
					<button type="button" class="wpps-ts-accordion-header" id="<?php echo esc_attr( $uid ); ?>_acc_head_sessions" aria-expanded="false" aria-controls="<?php echo esc_attr( $uid ); ?>_acc_body_sessions">
						<span class="wpps-ts-accordion-title"><?php esc_html_e( 'Active sessions', '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_sessions" role="region" aria-labelledby="<?php echo esc_attr( $uid ); ?>_acc_head_sessions">
						<?php include __DIR__ . '/views/sessions-panel.php'; ?>
					</div>
				</div>
			<?php endif; ?>

			<div class="wpps-ts-accordion">
				<button type="button" class="wpps-ts-accordion-header" id="<?php echo esc_attr( $uid ); ?>_acc_head_limits" aria-expanded="false" aria-controls="<?php echo esc_attr( $uid ); ?>_acc_body_limits">
					<span class="wpps-ts-accordion-title"><?php esc_html_e( 'Concurrent session limits', '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_limits" role="region" aria-labelledby="<?php echo esc_attr( $uid ); ?>_acc_head_limits">
					<table class="form-table" role="presentation">
						<tbody>
							<tr>
								<th scope="row">
									<label for="<?php echo esc_attr( $module_id ); ?>_limit_exceeded_action"><?php esc_html_e( 'When limit exceeded', 'wp-powersuite' ); ?></label>
								</th>
								<td>
									<select id="<?php echo esc_attr( $module_id ); ?>_limit_exceeded_action" class="wp-powersuite-advanced-setting" data-setting-key="limit_exceeded_action" name="<?php echo esc_attr( $module_id ); ?>[limit_exceeded_action]">
										<option value="logout_oldest" <?php selected( $limit_action, 'logout_oldest' ); ?>><?php esc_html_e( 'Log out oldest session(s)', 'wp-powersuite' ); ?></option>
										<option value="block_login" <?php selected( $limit_action, 'block_login' ); ?>><?php esc_html_e( 'Block new login', 'wp-powersuite' ); ?></option>
									</select>
									<p class="description"><?php esc_html_e( 'Block new login rejects the incoming sign-in. Existing excess sessions are still trimmed during background checks.', 'wp-powersuite' ); ?></p>
								</td>
							</tr>
							<tr>
								<th scope="row">
									<label for="<?php echo esc_attr( $module_id ); ?>_init_throttle_minutes"><?php esc_html_e( 'Background check interval', 'wp-powersuite' ); ?></label>
								</th>
								<td>
									<input
										type="number"
										min="1"
										max="60"
										class="small-text wp-powersuite-advanced-setting"
										data-setting-key="init_throttle_minutes"
										id="<?php echo esc_attr( $module_id ); ?>_init_throttle_minutes"
										name="<?php echo esc_attr( $module_id ); ?>[init_throttle_minutes]"
										value="<?php echo esc_attr( (string) (int) ( $settings['init_throttle_minutes'] ?? 10 ) ); ?>"
									/>
									<span><?php esc_html_e( 'minutes per user', 'wp-powersuite' ); ?></span>
									<p class="description"><?php esc_html_e( 'How often to reconcile session counts while a user is browsing. Lower values are stricter but use more resources.', 'wp-powersuite' ); ?></p>
								</td>
							</tr>
							<tr>
								<th scope="row"><?php esc_html_e( 'Limit notice', 'wp-powersuite' ); ?></th>
								<td>
									<label>
										<input type="checkbox" class="wp-powersuite-advanced-setting" data-setting-key="show_limit_notice" name="<?php echo esc_attr( $module_id ); ?>[show_limit_notice]" value="1" <?php checked( ! empty( $settings['show_limit_notice'] ) ); ?> />
										<?php esc_html_e( 'Show a notice when an older session was removed due to the limit (admin, frontend, and WooCommerce account)', 'wp-powersuite' ); ?>
									</label>
								</td>
							</tr>
							<tr>
								<th scope="row"><?php esc_html_e( 'Max sessions by role', 'wp-powersuite' ); ?></th>
								<td>
									<p class="description" style="margin-bottom: 8px;"><?php esc_html_e( 'Set 0 for unlimited. Limits apply to the user’s highest matching role cap.', 'wp-powersuite' ); ?></p>
									<div class="wpps-lsm-role-limits">
										<?php foreach ( $all_roles as $role_key => $role_data ) : ?>
											<?php
											$role_key = sanitize_key( (string) $role_key );
											$max      = isset( $role_max[ $role_key ] ) ? (int) $role_max[ $role_key ] : 0;
											?>
											<label class="wpps-lsm-role-limit">
												<span class="wpps-lsm-role-limit__name"><?php echo esc_html( translate_user_role( $role_data['name'] ) ); ?></span>
												<input
													type="number"
													min="0"
													max="50"
													class="small-text wp-powersuite-advanced-setting wpps-lsm-role-limit__input"
													data-setting-key="role_max_sessions.<?php echo esc_attr( $role_key ); ?>"
													name="<?php echo esc_attr( $module_id ); ?>[role_max_sessions][<?php echo esc_attr( $role_key ); ?>]"
													value="<?php echo esc_attr( (string) $max ); ?>"
													aria-label="<?php echo esc_attr( sprintf( __( 'Max sessions for %s', 'wp-powersuite' ), translate_user_role( $role_data['name'] ) ) ); ?>"
												/>
											</label>
										<?php endforeach; ?>
									</div>
								</td>
							</tr>
							<tr>
								<th scope="row">
									<label><?php esc_html_e( 'Excluded roles', 'wp-powersuite' ); ?></label>
								</th>
								<td>
									<?php if ( empty( $all_roles ) ) : ?>
										<p class="description"><?php esc_html_e( 'No roles found.', 'wp-powersuite' ); ?></p>
									<?php else : ?>
										<p class="description" style="margin-bottom: 8px;"><?php esc_html_e( 'Roles listed here ignore session limits entirely. Uncheck Administrator if you want admin session caps to apply.', 'wp-powersuite' ); ?></p>
										<div class="wpps-ct-multiselect" id="<?php echo esc_attr( $module_id ); ?>_excluded_roles_ms"
											data-label-none="<?php echo esc_attr( __( 'No roles excluded', 'wp-powersuite' ) ); ?>"
											data-label-single="<?php echo esc_attr( __( '1 role excluded', 'wp-powersuite' ) ); ?>"
											data-label-multi="<?php echo esc_attr( __( '%d roles excluded', 'wp-powersuite' ) ); ?>">
											<button type="button" class="wpps-ct-multiselect__trigger" aria-expanded="false" aria-haspopup="listbox" aria-controls="<?php echo esc_attr( $module_id ); ?>_excluded_roles_list">
												<span class="wpps-ct-multiselect__trigger-text"><?php esc_html_e( 'No roles excluded', '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 ); ?>_excluded_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_data ) : ?>
														<?php
														$role_key = sanitize_key( (string) $role_key );
														$label    = translate_user_role( $role_data['name'] );
														$checked  = in_array( $role_key, $excluded_roles, true );
														?>
														<label class="wpps-ct-multiselect__option" data-slug="<?php echo esc_attr( $role_key ); ?>" data-label="<?php echo esc_attr( $label ); ?>">
															<input
																type="checkbox"
																name="<?php echo esc_attr( $module_id ); ?>[excluded_roles][]"
																class="wp-powersuite-advanced-setting"
																data-setting-key="excluded_roles"
																value="<?php echo esc_attr( $role_key ); ?>"
																<?php checked( $checked ); ?>
															/>
															<span class="wpps-ct-multiselect__option-label"><?php echo esc_html( $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>
						</tbody>
					</table>
				</div>
			</div>

		</div>
	</form>

	<?php if ( ! $can_manage_sessions ) : ?>
		<p class="description"><?php esc_html_e( 'You need permission to edit users to view and revoke sessions for other accounts.', 'wp-powersuite' ); ?></p>
	<?php endif; ?>
</div>
