<?php
/**
 * Activity Log Admin Page View
 *
 * @package AdvancedUserActivityLog
 * @since 1.0.0
 */

// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

use WP_PowerSuite\Admin\PageHero;

$wpps_al_stats      = isset( $stats ) && is_array( $stats ) ? $stats : [];
$wpps_al_export     = isset( $export_url ) ? $export_url : '';
$wpps_al_roles      = isset( $roles ) && is_array( $roles ) ? $roles : [];
$wpps_al_severities = [
	''         => __( 'All severities', 'wp-powersuite' ),
	'critical' => __( 'Critical', 'wp-powersuite' ),
	'warning'  => __( 'Warning', 'wp-powersuite' ),
	'success'  => __( 'Success', 'wp-powersuite' ),
	'info'     => __( 'Info', 'wp-powersuite' ),
];

$wpps_al_meta_html = sprintf(
	'<a href="%1$s" class="button button-secondary"><span class="dashicons dashicons-admin-plugins" aria-hidden="true"></span> %2$s</a>',
	esc_url( admin_url( 'admin.php?page=powersuite' ) ),
	esc_html__( 'WP PowerSuite', 'wp-powersuite' )
);

$wpps_al_hero_stats = [];
if ( ! empty( $wpps_al_stats ) ) {
	$wpps_al_hero_stats = [
		[
			'value' => number_format_i18n( $wpps_al_stats['total'] ?? 0 ),
			'label' => __( 'Total entries', 'wp-powersuite' ),
		],
		[
			'value' => number_format_i18n( $wpps_al_stats['today'] ?? 0 ),
			'label' => __( 'Today', 'wp-powersuite' ),
		],
		[
			'value' => number_format_i18n( $wpps_al_stats['failed_30d'] ?? 0 ),
			'label' => __( 'Failed logins (30d)', 'wp-powersuite' ),
		],
		[
			'value' => number_format_i18n( $wpps_al_stats['unique_users'] ?? 0 ),
			'label' => __( 'Active users', 'wp-powersuite' ),
		],
	];
}
?>

<div class="wrap wpps-al-wrap">
	<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 cleared successfully.', 'wp-powersuite' ); ?></p>
		</div>
	<?php endif; ?>

	<?php if ( isset( $_GET['deleted'] ) && $_GET['deleted'] > 0 ) : ?>
		<div class="notice notice-success is-dismissible">
			<p>
				<?php
				printf(
					/* translators: %d: number of deleted logs */
					esc_html( _n( '%d log entry deleted.', '%d log entries deleted.', absint( $_GET['deleted'] ), 'wp-powersuite' ) ),
					absint( $_GET['deleted'] )
				);
				?>
			</p>
		</div>
	<?php endif; ?>

	<?php
	PageHero::render_for_module(
		[
			'icon'      => 'dashicons-clipboard',
			'title'     => __( 'Activity Log', 'wp-powersuite' ),
			'tagline'   => __( 'Track logins, content changes, plugins, themes, and settings for security auditing and troubleshooting.', 'wp-powersuite' ),
			'stats'     => $wpps_al_hero_stats,
			'meta_html' => $wpps_al_meta_html,
		]
	);
	?>

	<div class="wpps-al-card">
		<h2 class="wpps-al-card-title"><?php esc_html_e( 'Filters', 'wp-powersuite' ); ?></h2>
		<div class="wpps-al-card-body">
			<form method="get" action="" class="wpps-al-filters-form">
				<input type="hidden" name="page" value="wpps-activity-log" />

				<div class="wpps-al-filter-row wpps-al-filter-row-primary">
					<div class="wpps-al-filter-group">
						<label for="s"><?php esc_html_e( 'Search', 'wp-powersuite' ); ?></label>
						<input type="search" id="s" name="s" value="<?php echo esc_attr( $search ); ?>" placeholder="<?php esc_attr_e( 'Description, user, object, IP…', 'wp-powersuite' ); ?>" />
					</div>

					<div class="wpps-al-filter-group">
						<label for="filter_action"><?php esc_html_e( 'Action', 'wp-powersuite' ); ?></label>
						<select id="filter_action" name="filter_action">
							<option value=""><?php esc_html_e( 'All actions', 'wp-powersuite' ); ?></option>
							<?php foreach ( $actions as $action ) : ?>
								<option value="<?php echo esc_attr( $action ); ?>" <?php selected( $filter_action, $action ); ?>>
									<?php echo esc_html( ucwords( str_replace( '_', ' ', $action ) ) ); ?>
								</option>
							<?php endforeach; ?>
						</select>
					</div>

					<div class="wpps-al-filter-group">
						<label for="filter_severity"><?php esc_html_e( 'Severity', 'wp-powersuite' ); ?></label>
						<select id="filter_severity" name="filter_severity">
							<?php foreach ( $wpps_al_severities as $sev_key => $sev_label ) : ?>
								<option value="<?php echo esc_attr( $sev_key ); ?>" <?php selected( isset( $filter_severity ) ? $filter_severity : '', $sev_key ); ?>>
									<?php echo esc_html( $sev_label ); ?>
								</option>
							<?php endforeach; ?>
						</select>
					</div>

					<div class="wpps-al-filter-group">
						<label for="filter_user"><?php esc_html_e( 'User', 'wp-powersuite' ); ?></label>
						<select id="filter_user" name="filter_user">
							<option value="0"><?php esc_html_e( 'All users', 'wp-powersuite' ); ?></option>
							<?php foreach ( $users as $user ) : ?>
								<option value="<?php echo esc_attr( $user->ID ); ?>" <?php selected( $filter_user, $user->ID ); ?>>
									<?php echo esc_html( $user->user_login ); ?>
								</option>
							<?php endforeach; ?>
						</select>
					</div>

					<div class="wpps-al-filter-group">
						<label for="filter_role"><?php esc_html_e( 'Role', 'wp-powersuite' ); ?></label>
						<select id="filter_role" name="filter_role">
							<option value=""><?php esc_html_e( 'All roles', 'wp-powersuite' ); ?></option>
							<?php foreach ( $wpps_al_roles as $role_slug ) : ?>
								<option value="<?php echo esc_attr( $role_slug ); ?>" <?php selected( isset( $filter_role ) ? $filter_role : '', $role_slug ); ?>>
									<?php echo esc_html( $role_slug ); ?>
								</option>
							<?php endforeach; ?>
						</select>
					</div>
				</div>

				<div class="wpps-al-filter-row wpps-al-filter-row-secondary">
					<div class="wpps-al-filter-group">
						<label for="date_from"><?php esc_html_e( 'From date', 'wp-powersuite' ); ?></label>
						<input type="date" id="date_from" name="date_from" value="<?php echo esc_attr( isset( $date_from ) ? $date_from : '' ); ?>" />
					</div>
					<div class="wpps-al-filter-group">
						<label for="date_to"><?php esc_html_e( 'To date', 'wp-powersuite' ); ?></label>
						<input type="date" id="date_to" name="date_to" value="<?php echo esc_attr( isset( $date_to ) ? $date_to : '' ); ?>" />
					</div>
					<div class="wpps-al-filter-group">
						<label for="filter_ip"><?php esc_html_e( 'IP contains', 'wp-powersuite' ); ?></label>
						<input type="text" id="filter_ip" name="filter_ip" value="<?php echo esc_attr( isset( $filter_ip ) ? $filter_ip : '' ); ?>" placeholder="<?php esc_attr_e( 'e.g. 192.168', 'wp-powersuite' ); ?>" />
					</div>
					<div class="wpps-al-filter-group">
						<label for="filter_object_type"><?php esc_html_e( 'Object type', 'wp-powersuite' ); ?></label>
						<select id="filter_object_type" name="filter_object_type">
							<option value=""><?php esc_html_e( 'All types', 'wp-powersuite' ); ?></option>
							<?php foreach ( $object_types as $type ) : ?>
								<option value="<?php echo esc_attr( $type ); ?>" <?php selected( $filter_object_type, $type ); ?>>
									<?php echo esc_html( ucwords( str_replace( '_', ' ', $type ) ) ); ?>
								</option>
							<?php endforeach; ?>
						</select>
					</div>

					<div class="wpps-al-filter-group wpps-al-filter-group--actions" role="group" aria-labelledby="wpps-al-filter-actions-label">
						<span id="wpps-al-filter-actions-label" class="wpps-al-filter-group-label"><?php esc_html_e( 'Actions', 'wp-powersuite' ); ?></span>
						<div class="wpps-al-filter-actions">
							<button type="submit" class="wpps-al-btn wpps-al-btn-primary"><?php esc_html_e( 'Apply filters', 'wp-powersuite' ); ?></button>
							<a href="<?php echo esc_url( admin_url( 'admin.php?page=wpps-activity-log' ) ); ?>" class="wpps-al-btn wpps-al-btn-secondary"><?php esc_html_e( 'Reset', 'wp-powersuite' ); ?></a>
						</div>
					</div>
				</div>
			</form>
		</div>
	</div>

	<?php if ( ! empty( $logs ) ) : ?>
		<?php
		$pagination_args = [ 'page' => 'wpps-activity-log' ];
		if ( ! empty( $search ) ) {
			$pagination_args['s'] = $search;
		}
		if ( ! empty( $filter_action ) ) {
			$pagination_args['filter_action'] = $filter_action;
		}
		if ( ! empty( $filter_severity ) ) {
			$pagination_args['filter_severity'] = $filter_severity;
		}
		if ( ! empty( $filter_user ) ) {
			$pagination_args['filter_user'] = $filter_user;
		}
		if ( ! empty( $filter_role ) ) {
			$pagination_args['filter_role'] = $filter_role;
		}
		if ( ! empty( $filter_object_type ) ) {
			$pagination_args['filter_object_type'] = $filter_object_type;
		}
		if ( ! empty( $date_from ) ) {
			$pagination_args['date_from'] = $date_from;
		}
		if ( ! empty( $date_to ) ) {
			$pagination_args['date_to'] = $date_to;
		}
		if ( ! empty( $filter_ip ) ) {
			$pagination_args['filter_ip'] = $filter_ip;
		}
		
		$pagination_base = add_query_arg( $pagination_args, admin_url( 'admin.php' ) );
		$pagination_base = esc_url_raw( add_query_arg( 'paged', '%#%', $pagination_base ) );

		$per_page        = isset( $per_page ) ? (int) $per_page : 50;
		$pagination_from = $total_logs > 0 ? (int) ( ( $current_page - 1 ) * $per_page + 1 ) : 0;
		$pagination_to   = $total_logs > 0 ? (int) min( $current_page * $per_page, $total_logs ) : 0;
		?>

		<div class="wpps-al-list">
			<div class="wpps-al-toolbar">
				<div class="wpps-al-toolbar-main">
					<span class="wpps-al-toolbar-count">
						<?php
						printf(
							/* translators: %d: number of logs */
							esc_html( _n( '%d log entry', '%d log entries', $total_logs, 'wp-powersuite' ) ),
							esc_html( number_format_i18n( $total_logs ) )
						);
						?>
					</span>
				</div>
				<div class="wpps-al-toolbar-actions">
					<button type="button" class="wpps-al-btn wpps-al-btn-secondary wpps-clear-logs" data-nonce="<?php echo esc_attr( wp_create_nonce( 'wpps_activity_log_clear' ) ); ?>">
						<?php esc_html_e( 'Clear all logs', 'wp-powersuite' ); ?>
					</button>
					<a href="<?php echo esc_url( $wpps_al_export ? $wpps_al_export : wp_nonce_url( admin_url( 'admin-ajax.php?action=wpps_activity_log_export' ), 'wpps_activity_log_export', 'nonce' ) ); ?>" class="wpps-al-btn wpps-al-btn-primary">
						<span class="dashicons dashicons-download" aria-hidden="true"></span>
						<?php esc_html_e( 'Export CSV', 'wp-powersuite' ); ?>
					</a>
				</div>
			</div>
		<form id="posts-filter" class="wpps-al-list-form" method="post" action="<?php echo esc_url( admin_url( 'admin.php' ) ); ?>">
			<?php wp_nonce_field( 'bulk-logs' ); ?>
			<input type="hidden" name="page" value="wpps-activity-log" />
			<?php if ( ! empty( $search ) ) : ?>
				<input type="hidden" name="s" value="<?php echo esc_attr( $search ); ?>" />
			<?php endif; ?>
			<?php if ( ! empty( $filter_action ) ) : ?>
				<input type="hidden" name="filter_action" value="<?php echo esc_attr( $filter_action ); ?>" />
			<?php endif; ?>
			<?php if ( ! empty( $filter_user ) ) : ?>
				<input type="hidden" name="filter_user" value="<?php echo esc_attr( $filter_user ); ?>" />
			<?php endif; ?>
			<?php if ( ! empty( $filter_object_type ) ) : ?>
				<input type="hidden" name="filter_object_type" value="<?php echo esc_attr( $filter_object_type ); ?>" />
			<?php endif; ?>
			<?php if ( ! empty( $filter_severity ) ) : ?>
				<input type="hidden" name="filter_severity" value="<?php echo esc_attr( $filter_severity ); ?>" />
			<?php endif; ?>
			<?php if ( ! empty( $filter_role ) ) : ?>
				<input type="hidden" name="filter_role" value="<?php echo esc_attr( $filter_role ); ?>" />
			<?php endif; ?>
			<?php if ( ! empty( $date_from ) ) : ?>
				<input type="hidden" name="date_from" value="<?php echo esc_attr( $date_from ); ?>" />
			<?php endif; ?>
			<?php if ( ! empty( $date_to ) ) : ?>
				<input type="hidden" name="date_to" value="<?php echo esc_attr( $date_to ); ?>" />
			<?php endif; ?>
			<?php if ( ! empty( $filter_ip ) ) : ?>
				<input type="hidden" name="filter_ip" value="<?php echo esc_attr( $filter_ip ); ?>" />
			<?php endif; ?>

		<div class="tablenav top">
			<div class="alignleft actions bulkactions">
				<label for="bulk-action-selector-top" class="screen-reader-text"><?php esc_html_e( 'Select bulk action', 'wp-powersuite' ); ?></label>
				<select name="action" id="bulk-action-selector-top">
					<option value="-1"><?php esc_html_e( 'Bulk Actions', 'wp-powersuite' ); ?></option>
					<option value="delete"><?php esc_html_e( 'Delete', 'wp-powersuite' ); ?></option>
				</select>
				<button type="button" id="doaction" class="button action"><?php esc_html_e( 'Apply', 'wp-powersuite' ); ?></button>
			</div>
			<?php if ( $total_pages > 1 ) : ?>
				<div class="tablenav-pages">
					<span class="displaying-num">
						<?php
						printf(
							/* translators: 1: First visible row number, 2: last visible row number, 3: total rows (Posts/Pages style). */
							esc_html__( '%1$s–%2$s of %3$s items', 'wp-powersuite' ),
							esc_html( number_format_i18n( $pagination_from ) ),
							esc_html( number_format_i18n( $pagination_to ) ),
							esc_html( number_format_i18n( $total_logs ) )
						);
						?>
					</span>
					<span class="pagination-links">
						<?php
						echo paginate_links(
							[
								'base'      => $pagination_base,
								'format'    => '',
								'prev_text' => __( '&laquo;', 'default' ),
								'next_text' => __( '&raquo;', 'default' ),
								'total'     => $total_pages,
								'current'   => $current_page,
								'end_size'  => 1,
								'mid_size'  => 2,
								'type'      => 'plain',
							]
						);
						?>
					</span>
				</div>
			<?php else : ?>
				<div class="tablenav-pages one-page">
					<span class="displaying-num"><?php printf( esc_html__( '%s items', 'wp-powersuite' ), number_format_i18n( $total_logs ) ); ?></span>
				</div>
			<?php endif; ?>
		</div>

			<table class="wp-list-table widefat striped table-view-list">
				<thead>
					<tr>
						<td id="cb" class="manage-column column-cb check-column">
							<label for="cb-select-all-1" class="screen-reader-text"><?php esc_html_e( 'Select all', 'wp-powersuite' ); ?></label>
							<input id="cb-select-all-1" type="checkbox">
						</td>
						<th scope="col" id="wpps-al-col-date" class="manage-column column-date"><?php esc_html_e( 'Date', 'wp-powersuite' ); ?></th>
						<th scope="col" class="manage-column column-author"><?php esc_html_e( 'User', 'wp-powersuite' ); ?></th>
						<th scope="col" class="manage-column column-role"><?php esc_html_e( 'Role', 'wp-powersuite' ); ?></th>
						<th scope="col" class="manage-column column-action"><?php esc_html_e( 'Action', 'wp-powersuite' ); ?></th>
						<th scope="col" class="manage-column column-primary column-description"><?php esc_html_e( 'Description', 'wp-powersuite' ); ?></th>
						<th scope="col" class="manage-column column-ip"><?php esc_html_e( 'IP / location', 'wp-powersuite' ); ?></th>
					</tr>
				</thead>
				<tbody id="the-list">
					<?php foreach ( $logs as $log ) : ?>
						<?php
						$wpps_sev = \AdvancedUserActivityLog\Module::getSeverityForAction( (string) $log->action );
						?>
						<tr>
							<th scope="row" class="check-column">
								<label class="screen-reader-text" for="cb-select-<?php echo esc_attr( $log->id ); ?>"><?php esc_html_e( 'Select log entry', 'wp-powersuite' ); ?></label>
								<input id="cb-select-<?php echo esc_attr( $log->id ); ?>" type="checkbox" name="log[]" value="<?php echo esc_attr( $log->id ); ?>">
							</th>
							<td class="column-date" data-label="<?php esc_attr_e( 'Date', 'wp-powersuite' ); ?>">
							<?php
							echo esc_html( date_i18n( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), strtotime( $log->created_at ) ) );
							?>
						</td>
						<td class="author column-author" data-label="<?php esc_attr_e( 'User', 'wp-powersuite' ); ?>">
							<?php if ( $log->user_id ) : ?>
								<?php
								$user = get_userdata( $log->user_id );
								if ( $user ) {
									echo esc_html( $user->user_login );
								} else {
									echo esc_html( $log->user_login ?? 'Unknown' );
								}
								?>
							<?php else : ?>
								<span class="wpps-system-user"><?php esc_html_e( 'System', 'wp-powersuite' ); ?></span>
							<?php endif; ?>
						</td>
						<td class="column-role" data-label="<?php esc_attr_e( 'Role', 'wp-powersuite' ); ?>">
							<code class="wpps-role-pill"><?php echo esc_html( isset( $log->user_role ) && $log->user_role !== '' ? $log->user_role : '—' ); ?></code>
						</td>
						<td class="column-action" data-label="<?php esc_attr_e( 'Action', 'wp-powersuite' ); ?>">
							<span class="wpps-action-badge wpps-severity-<?php echo esc_attr( $wpps_sev ); ?> wpps-action-<?php echo esc_attr( $log->action ); ?>">
								<?php echo esc_html( ucwords( str_replace( '_', ' ', $log->action ) ) ); ?>
							</span>
						</td>
						<td class="column-description" data-label="<?php esc_attr_e( 'Description', 'wp-powersuite' ); ?>">
							<?php echo esc_html( $log->description ); ?>
						</td>
						<td class="column-ip" data-label="<?php esc_attr_e( 'IP Details', 'wp-powersuite' ); ?>">
							<div class="wpps-ip-details">
								<div class="wpps-ip-address">
									<code><?php echo esc_html( $log->ip_address ?? 'N/A' ); ?></code>
								</div>
								<?php if ( ! empty( $log->country ) || ! empty( $log->country_code ) ) : ?>
									<div class="wpps-ip-country">
										<span class="dashicons dashicons-admin-site"></span>
										<span class="wpps-country-name"><?php echo esc_html( $log->country ?? $log->country_code ?? '' ); ?></span>
									</div>
								<?php endif; ?>
							</div>
						</td>
					</tr>
				<?php endforeach; ?>
				</tbody>
			</table>

			<!-- Pagination Bottom -->
			<div class="tablenav bottom">
				<div class="alignleft actions bulkactions">
					<label for="bulk-action-selector-bottom" class="screen-reader-text"><?php esc_html_e( 'Select bulk action', 'wp-powersuite' ); ?></label>
					<select id="bulk-action-selector-bottom" name="action2">
						<option value="-1"><?php esc_html_e( 'Bulk Actions', 'wp-powersuite' ); ?></option>
						<option value="delete"><?php esc_html_e( 'Delete', 'wp-powersuite' ); ?></option>
					</select>
					<input type="button" id="doaction2" class="button action" value="<?php esc_attr_e( 'Apply', 'wp-powersuite' ); ?>">
				</div>
				<?php if ( $total_pages > 1 ) : ?>
					<div class="tablenav-pages">
						<span class="displaying-num">
							<?php
							printf(
								/* translators: 1: First visible row number, 2: last visible row number, 3: total rows. */
								esc_html__( '%1$s–%2$s of %3$s items', 'wp-powersuite' ),
								esc_html( number_format_i18n( $pagination_from ) ),
								esc_html( number_format_i18n( $pagination_to ) ),
								esc_html( number_format_i18n( $total_logs ) )
							);
							?>
						</span>
						<span class="pagination-links">
							<?php
							echo paginate_links(
								[
									'base'      => $pagination_base,
									'format'    => '',
									'prev_text' => __( '&laquo;', 'default' ),
									'next_text' => __( '&raquo;', 'default' ),
									'total'     => $total_pages,
									'current'   => $current_page,
									'end_size'  => 1,
									'mid_size'  => 2,
									'type'      => 'plain',
								]
							);
							?>
						</span>
					</div>
				<?php else : ?>
					<div class="tablenav-pages one-page">
						<span class="displaying-num"><?php printf( esc_html__( '%s items', 'wp-powersuite' ), number_format_i18n( $total_logs ) ); ?></span>
					</div>
				<?php endif; ?>
			</div>
		</form>
		</div>
	<?php else : ?>
		<div class="wpps-al-empty-state">
			<div class="wpps-al-empty-icon" aria-hidden="true">
				<span class="dashicons dashicons-clipboard"></span>
			</div>
			<h2 class="wpps-al-empty-title"><?php esc_html_e( 'No activity logs match your filters', 'wp-powersuite' ); ?></h2>
			<p class="wpps-al-empty-desc"><?php esc_html_e( 'Reset filters or use the site to generate events—logins, edits, and setting changes will appear here.', 'wp-powersuite' ); ?></p>
			<a href="<?php echo esc_url( admin_url( 'admin.php?page=wpps-activity-log' ) ); ?>" class="wpps-al-btn wpps-al-btn-primary"><?php esc_html_e( 'View all logs', 'wp-powersuite' ); ?></a>
		</div>
	<?php endif; ?>
</div>
