<?php
/**
 * Limit Login Attempts — logs admin view.
 *
 * @package LimitLoginAttempts
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

use WP_PowerSuite\Admin\PageHero;

$date_format     = get_option( 'date_format', 'Y-m-d' );
$time_format     = get_option( 'time_format', 'H:i:s' );
$datetime_format = $date_format . ' ' . $time_format;
?>
<div class="wrap wpps-login-logs">
	<hr class="wp-header-end" style="margin:0;padding:0;border:none;height:0;overflow:hidden;">

	<?php if ( isset( $_GET['cleared'] ) && $_GET['cleared'] === '1' ) : ?>
		<div class="notice notice-success is-dismissible">
			<p><?php esc_html_e( 'Logs and active lockouts cleared successfully.', 'wppowersuite-lite' ); ?></p>
		</div>
	<?php endif; ?>

	<?php if ( isset( $_GET['unblocked'] ) && $_GET['unblocked'] === '1' ) : ?>
		<div class="notice notice-success is-dismissible">
			<p><?php esc_html_e( 'IP address unblocked successfully.', 'wppowersuite-lite' ); ?></p>
		</div>
	<?php endif; ?>

	<?php
	$module_settings_btn = sprintf(
		'<button type="button" class="button button-secondary" id="wpps-ll-open-settings"><span class="dashicons dashicons-admin-generic" aria-hidden="true"></span> %s</button>',
		esc_html__( 'Module Settings', 'wppowersuite-lite' )
	);

	PageHero::render_for_module(
		[
			'icon'      => 'dashicons-shield',
			'title'     => __( 'Failed Login Attempts Log', 'wppowersuite-lite' ),
			'tagline'   => __( 'Review blocked IPs, failed usernames, and active lockouts from brute-force login attempts.', 'wppowersuite-lite' ),
			'meta_html' => $module_settings_btn,
		]
	);
	?>

	<div class="wpps-ll-panel">
		<h2 class="wpps-ll-panel-title">
			<?php esc_html_e( 'Recent attempts', 'wppowersuite-lite' ); ?>
			<span class="wpps-ll-count">
				<?php
				printf(
					/* translators: %d: total log count */
					esc_html__( '%d total', 'wppowersuite-lite' ),
					(int) $total_logs
				);
				?>
			</span>
		</h2>

		<div class="wpps-ll-toolbar">
			<form method="get" action="" class="wpps-ll-filters">
				<input type="hidden" name="page" value="wpps-limit-login-attempts-logs" />

				<div class="wpps-ll-filter-group">
					<label for="wpps-ll-search"><?php esc_html_e( 'Search', 'wppowersuite-lite' ); ?></label>
					<input type="search" id="wpps-ll-search" name="s" value="<?php echo esc_attr( $search ); ?>" placeholder="<?php esc_attr_e( 'Search by IP or username…', 'wppowersuite-lite' ); ?>" />
				</div>

				<div class="wpps-ll-filter-group">
					<label for="wpps-ll-filter-ip"><?php esc_html_e( 'IP address', 'wppowersuite-lite' ); ?></label>
					<select id="wpps-ll-filter-ip" name="filter_ip">
						<option value=""><?php esc_html_e( 'All IPs', 'wppowersuite-lite' ); ?></option>
						<?php foreach ( $unique_ips as $ip ) : ?>
							<option value="<?php echo esc_attr( $ip ); ?>" <?php selected( $filter_ip, $ip ); ?>>
								<?php echo esc_html( $ip ); ?>
							</option>
						<?php endforeach; ?>
					</select>
				</div>

				<div class="wpps-ll-filter-group">
					<label for="wpps-ll-filter-country"><?php esc_html_e( 'Country', 'wppowersuite-lite' ); ?></label>
					<select id="wpps-ll-filter-country" name="filter_country">
						<option value=""><?php esc_html_e( 'All countries', 'wppowersuite-lite' ); ?></option>
						<?php foreach ( $unique_countries as $country_code ) : ?>
							<?php
							$country_name = isset( $module_instance ) ? $module_instance->getCountryName( $country_code ) : null;
							?>
							<option value="<?php echo esc_attr( $country_code ); ?>" <?php selected( $filter_country, $country_code ); ?>>
								<?php echo esc_html( strtoupper( $country_code ) . ( $country_name ? ' - ' . $country_name : '' ) ); ?>
							</option>
						<?php endforeach; ?>
					</select>
				</div>

				<div class="wpps-ll-filter-actions">
					<button type="submit" class="button button-primary"><?php esc_html_e( 'Filter', 'wppowersuite-lite' ); ?></button>
					<a href="<?php echo esc_url( admin_url( 'admin.php?page=wpps-limit-login-attempts-logs' ) ); ?>" class="button"><?php esc_html_e( 'Reset', 'wppowersuite-lite' ); ?></a>
				</div>
			</form>

			<?php if ( $total_logs > 0 ) : ?>
				<div class="wpps-ll-toolbar-actions">
					<button type="button" class="button wpps-ll-clear-btn wpps-clear-logs" data-nonce="<?php echo esc_attr( wp_create_nonce( 'wpps_limit_login_attempts_clear' ) ); ?>">
						<?php esc_html_e( 'Clear All Logs', 'wppowersuite-lite' ); ?>
					</button>
				</div>
			<?php endif; ?>
		</div>

		<?php if ( empty( $logs ) ) : ?>
			<div class="wpps-ll-empty">
				<span class="dashicons dashicons-shield" aria-hidden="true"></span>
				<h3><?php esc_html_e( 'No failed login attempts logged yet', 'wppowersuite-lite' ); ?></h3>
				<p class="description"><?php esc_html_e( 'Failed sign-in attempts and lockouts will appear here when someone tries incorrect passwords on your login form.', 'wppowersuite-lite' ); ?></p>
			</div>
		<?php else : ?>
			<?php
			$per_page = 50;
			$start    = ( $current_page - 1 ) * $per_page + 1;
			$end      = min( $current_page * $per_page, $total_logs );

			$pagination_args = [
				'page' => 'wpps-limit-login-attempts-logs',
			];
			if ( ! empty( $search ) ) {
				$pagination_args['s'] = $search;
			}
			if ( ! empty( $filter_ip ) ) {
				$pagination_args['filter_ip'] = $filter_ip;
			}
			if ( ! empty( $filter_country ) ) {
				$pagination_args['filter_country'] = $filter_country;
			}

			$pagination_base = add_query_arg( $pagination_args, admin_url( 'admin.php' ) );
			$pagination_base = esc_url_raw( add_query_arg( 'paged', '%#%', $pagination_base ) );
			?>

			<div class="wpps-ll-table-wrap">
				<div class="tablenav top">
					<div class="tablenav-pages">
						<span class="displaying-num">
							<?php
							printf(
								/* translators: 1: first visible row, 2: last visible row, 3: total rows */
								esc_html__( '%1$s–%2$s of %3$s items', 'wppowersuite-lite' ),
								esc_html( number_format_i18n( $start ) ),
								esc_html( number_format_i18n( $end ) ),
								esc_html( number_format_i18n( $total_logs ) )
							);
							?>
						</span>
						<?php if ( $total_pages > 1 ) : ?>
							<span class="pagination-links">
								<?php
								echo wp_kses_post(
									paginate_links(
										[
											'base'      => $pagination_base,
											'format'    => '',
											'prev_text' => '&laquo;',
											'next_text' => '&raquo;',
											'total'     => $total_pages,
											'current'   => $current_page,
											'end_size'  => 2,
											'mid_size'  => 2,
										]
									)
								);
								?>
							</span>
						<?php endif; ?>
					</div>
				</div>

				<table class="wp-list-table widefat fixed striped">
					<thead>
						<tr>
							<th scope="col"><?php esc_html_e( 'Date', 'wppowersuite-lite' ); ?></th>
							<th scope="col"><?php esc_html_e( 'IP Address', 'wppowersuite-lite' ); ?></th>
							<th scope="col"><?php esc_html_e( 'Country', 'wppowersuite-lite' ); ?></th>
							<th scope="col"><?php esc_html_e( 'Username', 'wppowersuite-lite' ); ?></th>
							<th scope="col"><?php esc_html_e( 'Attempts', 'wppowersuite-lite' ); ?></th>
							<th scope="col"><?php esc_html_e( 'Lockout Until', 'wppowersuite-lite' ); ?></th>
							<th scope="col"><?php esc_html_e( 'Actions', 'wppowersuite-lite' ); ?></th>
						</tr>
					</thead>
					<tbody>
						<?php foreach ( $logs as $log ) : ?>
							<?php
							$is_currently_locked = false;
							$lockout_time        = null;
							if ( ! empty( $log->lockout_until ) ) {
								$lockout_time = strtotime( $log->lockout_until );
							}
							if ( ! empty( $log->ip_address ) && isset( $module_instance ) ) {
								$is_currently_locked = $module_instance->isIpCurrentlyLocked( (string) $log->ip_address );
							}
							$created_timestamp = ! empty( $log->created_at ) ? strtotime( $log->created_at ) : false;
							?>
							<tr>
								<td>
									<?php
									if ( $created_timestamp !== false ) {
										echo esc_html( date_i18n( $datetime_format, $created_timestamp ) );
									} else {
										echo '—';
									}
									?>
								</td>
								<td><code><?php echo esc_html( $log->ip_address ?? '—' ); ?></code></td>
								<td>
									<?php
									$country_code = ! empty( $log->country_code ) ? strtolower( $log->country_code ) : null;
									if ( $country_code && isset( $module_instance ) ) {
										$country_name = $module_instance->getCountryName( $country_code );
										$flag_emoji   = $module_instance->getCountryFlag( $country_code );
										echo '<span title="' . esc_attr( $country_name ?: strtoupper( $country_code ) ) . '">';
										if ( $flag_emoji ) {
											echo esc_html( $flag_emoji ) . ' ';
										}
										echo esc_html( strtoupper( $country_code ) );
										if ( $country_name ) {
											echo ' <span class="wpps-login-log-country-name">(' . esc_html( $country_name ) . ')</span>';
										}
										echo '</span>';
									} else {
										echo '—';
									}
									?>
								</td>
								<td><?php echo esc_html( $log->username ?? '—' ); ?></td>
								<td><?php echo esc_html( $log->attempts ?? 0 ); ?></td>
								<td>
									<?php
									if ( ! empty( $log->lockout_until ) && $lockout_time ) {
										if ( $lockout_time > time() ) {
											echo '<span class="wpps-login-log-lockout-active">' . esc_html( date_i18n( $datetime_format, $lockout_time ) ) . '</span>';
										} else {
											echo '<span class="wpps-login-log-lockout-expired">' . esc_html__( 'Expired', 'wppowersuite-lite' ) . '</span>';
										}
									} else {
										echo '—';
									}
									?>
								</td>
								<td>
									<?php
									if ( $is_currently_locked ) {
										$unblock_url = wp_nonce_url(
											add_query_arg(
												[
													'page'   => 'wpps-limit-login-attempts-logs',
													'action' => 'unblock',
													'ip'     => $log->ip_address,
												],
												admin_url( 'admin.php' )
											),
											'unblock_ip_' . $log->ip_address
										);
										if ( ! empty( $search ) ) {
											$unblock_url = add_query_arg( 's', rawurlencode( $search ), $unblock_url );
										}
										if ( ! empty( $filter_ip ) ) {
											$unblock_url = add_query_arg( 'filter_ip', rawurlencode( $filter_ip ), $unblock_url );
										}
										if ( ! empty( $filter_country ) ) {
											$unblock_url = add_query_arg( 'filter_country', rawurlencode( $filter_country ), $unblock_url );
										}
										if ( $current_page > 1 ) {
											$unblock_url = add_query_arg( 'paged', $current_page, $unblock_url );
										}
										echo '<a href="' . esc_url( $unblock_url ) . '" class="button button-small" onclick="return confirm(\'' . esc_js( __( 'Are you sure you want to unblock this IP address?', 'wppowersuite-lite' ) ) . '\');">' . esc_html__( 'Unblock', 'wppowersuite-lite' ) . '</a>';
									} else {
										echo '—';
									}
									?>
								</td>
							</tr>
						<?php endforeach; ?>
					</tbody>
				</table>

				<?php if ( $total_pages > 1 ) : ?>
					<div class="tablenav bottom">
						<div class="tablenav-pages">
							<span class="displaying-num">
								<?php
								printf(
									/* translators: 1: first visible row, 2: last visible row, 3: total rows */
									esc_html__( '%1$s–%2$s of %3$s items', 'wppowersuite-lite' ),
									esc_html( number_format_i18n( $start ) ),
									esc_html( number_format_i18n( $end ) ),
									esc_html( number_format_i18n( $total_logs ) )
								);
								?>
							</span>
							<span class="pagination-links">
								<?php
								echo wp_kses_post(
									paginate_links(
										[
											'base'      => $pagination_base,
											'format'    => '',
											'prev_text' => '&laquo;',
											'next_text' => '&raquo;',
											'total'     => $total_pages,
											'current'   => $current_page,
											'end_size'  => 2,
											'mid_size'  => 2,
										]
									)
								);
								?>
							</span>
						</div>
					</div>
				<?php endif; ?>
			</div>
		<?php endif; ?>
	</div>
</div>

<div id="wp-powersuite-modal" class="wp-powersuite-modal" style="display: none;" aria-hidden="true">
	<div class="wp-powersuite-modal__overlay" tabindex="-1"></div>
	<div class="wp-powersuite-modal__content" role="dialog" aria-modal="true" aria-labelledby="wp-powersuite-modal-title">
		<div class="wp-powersuite-modal__header">
			<h2 id="wp-powersuite-modal-title" class="wp-powersuite-modal__title">
				<span class="dashicons dashicons-admin-settings" aria-hidden="true"></span>
				<?php esc_html_e( 'Advanced Settings', 'wppowersuite-lite' ); ?>
				<span class="wp-powersuite-modal__module-name"></span>
			</h2>
			<button type="button" class="wp-powersuite-modal__close" aria-label="<?php esc_attr_e( 'Close', 'wppowersuite-lite' ); ?>">
				<span class="dashicons dashicons-no-alt" aria-hidden="true"></span>
			</button>
		</div>
		<div class="wp-powersuite-modal__body">
			<div class="wp-powersuite-modal__loading" style="display: none;">
				<span class="spinner is-active"></span>
				<p><?php esc_html_e( 'Loading settings…', 'wppowersuite-lite' ); ?></p>
			</div>
			<div class="wp-powersuite-modal__settings"></div>
		</div>
		<div class="wp-powersuite-modal__footer">
			<button type="button" class="button wp-powersuite-modal__cancel">
				<?php esc_html_e( 'Cancel', 'wppowersuite-lite' ); ?>
			</button>
			<button type="button" class="button button-primary wp-powersuite-modal__save">
				<?php esc_html_e( 'Save Settings', 'wppowersuite-lite' ); ?>
			</button>
		</div>
	</div>
</div>
