<?php
/**
 * Admin integrations (Users column, assets, admin bar).
 *
 * @package LoginSessionManager
 */

namespace LoginSessionManager\Includes;

use WP_PowerSuite\Core\NetworkScope;

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

class Session_Admin {

	private Session_Repository $repository;

	/** @var array<string, mixed> */
	private array $settings;

	public function __construct( Session_Repository $repository, array $settings ) {
		$this->repository = $repository;
		$this->settings   = $settings;
	}

	public function register_hooks(): void {
		if ( ! Session_Capabilities::is_manager_active( $this->settings ) ) {
			return;
		}

		if ( ! empty( $this->settings['show_admin_bar'] ) ) {
			add_action( 'admin_bar_menu', [ $this, 'admin_bar_sessions' ], 100 );
		}

		if ( ! is_admin() ) {
			return;
		}

		add_action( 'admin_enqueue_scripts', [ $this, 'enqueue_assets' ] );

		if ( ! empty( $this->settings['show_users_column'] ) && user_can( get_current_user_id(), 'edit_users' ) ) {
			add_filter( 'manage_users_columns', [ $this, 'add_users_column' ] );
			add_filter( 'manage_users_custom_column', [ $this, 'render_users_column' ], 10, 3 );
		}
	}

	public function enqueue_assets( string $hook ): void {
		if ( ! Session_Capabilities::is_manager_active( $this->settings ) ) {
			return;
		}

		$is_powersuite = in_array( $hook, [ 'toplevel_page_powersuite', 'wp-powersuite_page_powersuite' ], true );
		$is_profile    = in_array( $hook, [ 'profile.php', 'user-edit.php', 'users.php' ], true );

		if ( ! $is_powersuite && ! ( $is_profile && ! empty( $this->settings['show_on_profile'] ) ) ) {
			return;
		}

		$this->enqueue_shared_assets();
	}

	public function enqueue_shared_assets(): void {
		wp_enqueue_style( 'dashicons' );
		wp_enqueue_style( 'wp-powersuite-admin' );

		$css_path = dirname( __DIR__ ) . '/assets/login-session-manager.css';
		$js_path  = dirname( __DIR__ ) . '/assets/login-session-manager.js';
		$css_ver  = file_exists( $css_path ) ? (string) filemtime( $css_path ) : '1.1.0';
		$js_ver   = file_exists( $js_path ) ? (string) filemtime( $js_path ) : '1.1.0';

		wp_enqueue_style(
			'wpps-login-session-manager',
			wp_powersuite_module_asset_url( dirname( __DIR__ ) . '/module.php', 'assets/login-session-manager.css' ),
			[ 'wp-powersuite-admin' ],
			$css_ver
		);

		wp_enqueue_script(
			'wpps-login-session-manager',
			wp_powersuite_module_asset_url( dirname( __DIR__ ) . '/module.php', 'assets/login-session-manager.js' ),
			[ 'jquery' ],
			$js_ver,
			true
		);

		wp_localize_script(
			'wpps-login-session-manager',
			'wppsLoginSessionManager',
			[
				'ajaxUrl'        => admin_url( 'admin-ajax.php' ),
				'nonce'          => wp_create_nonce( 'wpps_login_session_manager' ),
				'strings'        => [
					'confirmDestroy'     => __( 'Log out this session?', 'wp-powersuite' ),
					'confirmDestroyAll'  => __( 'Log out all sessions for this user?', 'wp-powersuite' ),
					'confirmDestroySite' => __( 'This will log out every user on the site. Continue?', 'wp-powersuite' ),
					'confirmBulk'        => __( 'Log out all sessions for the selected users?', 'wp-powersuite' ),
					'destroyed'          => __( 'Session revoked.', 'wp-powersuite' ),
					'error'              => __( 'Something went wrong. Please try again.', 'wp-powersuite' ),
					'loading'            => __( 'Loading…', 'wp-powersuite' ),
					'noSessions'         => __( 'No active sessions.', 'wp-powersuite' ),
					'currentSession'     => __( 'Current session', 'wp-powersuite' ),
					'loginAsBadge'       => __( 'Login as User', 'wp-powersuite' ),
					'tempLoginBadge'     => __( 'Temporary Login', 'wp-powersuite' ),
					'logOutSession'      => __( 'Log out session', 'wp-powersuite' ),
					'logOutEverywhere'   => __( 'Log out everywhere', 'wp-powersuite' ),
					'page'               => __( 'Page', 'wp-powersuite' ),
					'of'                 => __( 'of', 'wp-powersuite' ),
					'searchPlaceholder'  => __( 'Search users…', 'wp-powersuite' ),
				],
				'canDestroySite' => Session_Capabilities::can_destroy_all_site_wide( get_current_user_id() ),
				'filterUserId'   => 0,
				'perPage'        => 50,
			]
		);
	}

	/**
	 * @param array<string, string> $columns
	 * @return array<string, string>
	 */
	public function add_users_column( array $columns ): array {
		$columns['wpps_active_sessions'] = __( 'Active sessions', 'wp-powersuite' );
		return $columns;
	}

	public function render_users_column( string $output, string $column_name, int $user_id ): string {
		if ( $column_name !== 'wpps_active_sessions' ) {
			return $output;
		}

		$count = $this->repository->count_active_sessions( $user_id );
		$url   = get_edit_user_link( $user_id );

		if ( ! $url ) {
			$url = add_query_arg( 'user_id', $user_id, NetworkScope::adminUrl( 'user-edit.php' ) );
		}

		$url .= '#wpps-lsm-profile-sessions';

		if ( $count < 1 ) {
			return esc_html__( 'None', 'wp-powersuite' );
		}

		return sprintf(
			'<a href="%s">%s</a>',
			esc_url( $url ),
			esc_html(
				sprintf(
					/* translators: %d: session count */
					_n( '%d session', '%d sessions', $count, 'wp-powersuite' ),
					$count
				)
			)
		);
	}

	public function admin_bar_sessions( \WP_Admin_Bar $admin_bar ): void {
		if ( ! is_user_logged_in() || ! is_admin_bar_showing() ) {
			return;
		}

		$user_id = get_current_user_id();
		$count   = $this->repository->count_active_sessions( $user_id );

		if ( $count < 2 ) {
			return;
		}

		$href = get_edit_profile_url( $user_id ) . '#wpps-lsm-profile-sessions';
		if ( is_admin() && user_can( $user_id, 'edit_users' ) ) {
			$href = NetworkScope::adminUrl(
				'admin.php',
				[
					'page'         => 'powersuite',
					'wpps_module'  => 'login-session-manager',
					'wpps_section' => 'sessions',
				]
			);
		}

		$admin_bar->add_node(
			[
				'id'    => 'wpps-lsm-sessions',
				'title' => sprintf(
					/* translators: %d: active session count */
					__( '%d active sessions', 'wp-powersuite' ),
					$count
				),
				'href'  => $href,
				'meta'  => [ 'class' => 'wpps-lsm-admin-bar-sessions' ],
			]
		);
	}
}
