<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit; // Prevent direct access to the script.
}

global $current_user;
$sessions = get_user_meta( $current_user->ID, 'session_tokens', true );

if ( empty( $sessions ) && ! is_array( $sessions ) ) {
	return;
}
$current_token = hash( 'sha256', wp_get_session_token() );
$date_format   = get_option( 'date_format' );
$time_format   = get_option( 'time_format' );
?>
<div id="gn-security-sessions" class="gn-dashboard-section gn-section-sessions">
	<div class="gn-head">
		<h3 class="gn-title"><?php echo esc_html__( 'Logged-in sessions', 'gigneo' ); ?></h3>
	</div>
	<div class="gn-body">
		<div class="gn-table-wrapper gn-user-sessions">
			<table class="gn-table gn-user-sessions-table">
				<thead>
				<tr>
					<th><?php echo esc_html__( 'Browser', 'gigneo' ); ?></th>
					<th><?php echo esc_html__( 'Location', 'gigneo' ); ?></th>
					<th><?php echo esc_html__( 'IP Address', 'gigneo' ); ?></th>
					<th><?php echo esc_html__( 'Activity', 'gigneo' ); ?></th>
					<th><?php echo esc_html__( 'Status', 'gigneo' ); ?></th>
				</tr>
				</thead>
				<body>
				<?php
				foreach ( $sessions as $token => $data ) {
					$current    = $current_token === $token;
					$ip         = $data['ip'] ?? '';
					$location   = gigneo_get_ip_location( $ip );
					$location   = '' !== $location ? $location : '—';
					$browser    = ! empty( $data['ua'] ) ? gigneo_detect_browser( $data['ua'] ) : '';
					$login_time = isset( $data['login'] ) ? gmdate( "{$date_format} {$time_format}", $data['login'] ) : '';
					$login_time = isset( $data['login'] ) ? gigneo_datetime( $login_time, "{$date_format} – {$time_format}" ) : '';
					?>
					<tr>
						<td>
							<div class="gn-browser-info">
								<h5 class="gn-browser-name"><?php echo esc_html( $browser ); ?></h5>
							</div>
						</td>
						<td><?php echo esc_html( $location ); ?></td>
						<td><?php echo esc_html( $ip ); ?></td>
						<td><?php echo esc_html( $login_time ); ?></td>
						<td>
							<?php if ( $current ) { ?>
								<span class="gn-status-tag gn-success"><?php echo esc_html__( 'Current', 'gigneo' ); ?></span>
							<?php } else { ?>
								<button type="button" class="gn-btn gn-delete-user-session" data-session-key="<?php echo esc_attr( $token ); ?>">
									<i class="hi hi-trash" aria-hidden="true"></i>
								</button>
							<?php } ?>
						</td>
					</tr>
				<?php } ?>
				</body>
			</table>
		</div>
	</div>
</div>