<?php
/**
 * Temporary Login — token links, session scoping, optional notifications.
 *
 * @package TemporaryLogin
 */

namespace TemporaryLogin;

require_once __DIR__ . '/FeatureGate.php';
require_once __DIR__ . '/includes/class-temporary-login-email.php';

use WP_PowerSuite\Core\AbstractModule;
use WP_PowerSuite\Core\OptionStore;

/**
 * Temporary Login Module Class
 *
 * @since 1.0.0
 */
class Module extends AbstractModule {

	private const MODULE_ID = 'temporary-login';
	private const MODULE_VERSION = '1.2.7';
	private const LOG_RETENTION_DAYS = 90;
	private const TOKEN_PARAM = 'tl_token';
	private const DB_TABLE_NAME = 'tl_temporary_logins';
	private const DB_LOG_TABLE_NAME = 'tl_activity_logs';
	/**
	 * Legacy global session marker (deprecated). Sessions are per-browser via {@see SESSION_COOKIE_NAME}.
	 *
	 * @deprecated Stored only for cleanup; do not write on new logins.
	 */
	private const USER_META_SESSION_LOGIN = '_wpps_tl_session_login';
	/** Per-browser temp session cookie (login_id.user_id.hmac). */
	private const SESSION_COOKIE_NAME = 'wpps_tl_session';
	/** Set for users created via temporary-login email flow — password login / reset disabled */
	private const USER_META_PASSWORDLESS_ACCOUNT = '_wpps_tl_passwordless_only';
	private const TOKEN_RATE_TRANSIENT_PREFIX = 'tl_tok_fail_';
	private const DB_READY_OPTION = 'wpps_tl_db_ready';

	/**
	 * JSON object stored in allowed_capabilities (plugin/theme grants for the session).
	 *
	 * @see self::PERM_INSTALL_PLUGINS Keys written by encodeLoginPermissionsFromArgs().
	 */
	private const PERM_INSTALL_PLUGINS = 'install_plugins';
	private const PERM_DELETE_PLUGINS  = 'delete_plugins';
	private const PERM_INSTALL_THEMES  = 'install_themes';
	private const PERM_DELETE_THEMES   = 'delete_themes';

	/** Admin screens never available during a temporary session. */
	private const ALWAYS_BLOCKED_ADMIN_SCREENS = [
		'plugin-editor.php',
		'theme-editor.php',
		'update-core.php',
		'import.php',
		'export.php',
		'site-health.php',
	];

	/**
	 * WP PowerSuite admin pages blocked for temporary sessions.
	 * The module list (powersuite) and individual module screens remain available.
	 */
	private const BLOCKED_POWERSUITE_PAGES = [
		'powersuite-temporary-login',
		'powersuite-settings',
		'powersuite-license',
		'powersuite-performance',
	];

	private ?object $session_login_cache = null;

	/** @var array<string, bool>|null Role capabilities for the active temp session. */
	private ?array $session_role_caps_cache = null;

	/**
	 * Get Module ID
	 *
	 * @since 1.0.0
	 * @return string Module ID.
	 */
	public function getId(): string {
		return self::MODULE_ID;
	}

	/**
	 * Get Module Name
	 *
	 * @since 1.0.0
	 * @return string Module name.
	 */
	public function getName(): string {
		return __( 'Temporary Login', 'wp-powersuite' );
	}

	/**
	 * Get Module Version
	 *
	 * @since 1.0.0
	 * @return string Module version.
	 */
	public function getVersion(): string {
		return self::MODULE_VERSION;
	}

	/**
	 * Get Module Description
	 *
	 * @since 1.0.0
	 * @return string Module description.
	 */
	public function getDescription(): string {
		return __( 'Expiring, one-click login links for vendors or support—no shared passwords, with optional limits and a simple activity log.', 'wp-powersuite' );
	}

	/**
	 * Get Module Context
	 *
	 * @since 1.0.0
	 * @return string|array Module context.
	 */
	public function getContext(): string|array {
		return [ 'admin', 'frontend', 'ajax' ];
	}

	/**
	 * Get Module Dependencies
	 *
	 * @since 1.0.0
	 * @return array<string> Module dependencies.
	 */
	public function getDependencies(): array {
		return [];
	}

	/**
	 * Initialize Module
	 *
	 * Sets up hooks for temporary login functionality.
	 *
	 * @since 1.0.0
	 * @return void
	 */
	protected function registerHooks(): void {
		add_action( 'tl_cleanup_expired_logins', [ $this, 'cleanupExpiredLogins' ] );
		add_action( 'tl_cleanup_activity_logs', [ $this, 'cleanupOldActivityLogs' ] );

		if ( defined( 'DOING_CRON' ) && DOING_CRON ) {
			return;
		}

		add_action( 'wp_logout', [ $this, 'onWpLogoutClearSessionMeta' ], 10, 1 );
		add_filter( 'wp_authenticate_user', [ $this, 'preventPasswordLogin' ], 10, 2 );
		add_filter( 'wpps_2fa_allow_bypass', [ $this, 'allow2FABypassForTemporaryLogin' ], 10, 2 );
		add_filter( 'allow_password_reset', [ $this, 'disablePasswordReset' ], 10, 2 );
		add_filter( 'wpps_tl_is_token_login_request', [ $this, 'filterIsTokenLoginRequest' ], 10, 1 );

		if ( self::requestHasTokenParam() ) {
			add_action( 'template_redirect', [ $this, 'handleTemporaryLogin' ], 1 );
		}

		if ( ! empty( $_COOKIE[ self::SESSION_COOKIE_NAME ] ) ) {
			add_action( 'init', [ $this, 'cleanupLegacyGlobalSessionMeta' ], 0 );
			add_action( 'init', [ $this, 'maybeRegisterSessionHooks' ], 1 );
		}

		if ( wp_doing_ajax() || is_admin() ) {
			$this->registerAdminAjaxHandlers();
		}

		if ( is_admin() ) {
			add_action( 'admin_menu', [ $this, 'addAdminMenu' ], 20 );
			add_action( 'admin_enqueue_scripts', [ $this, 'enqueueAdminAssets' ] );
			add_filter( 'manage_users_columns', [ $this, 'addUsersListColumn' ] );
			add_filter( 'manage_users_custom_column', [ $this, 'renderUsersListColumn' ], 10, 3 );
		}
	}

	/**
	 * Revoke all links, invalidate sessions, and clear cron when the module is disabled.
	 */
	public static function cleanupOnDisable(): void {
		global $wpdb;

		if ( ! defined( 'WP_POWERSUITE_MODULES_DIR' ) ) {
			return;
		}

		$table = $wpdb->prefix . self::DB_TABLE_NAME;
		$found = $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $table ) );
		if ( $found !== $table ) {
			return;
		}

		$now = current_time( 'mysql' );
		$user_ids = $wpdb->get_col( "SELECT DISTINCT user_id FROM {$table}" );
		$wpdb->query(
			$wpdb->prepare(
				"UPDATE {$table} SET is_revoked = 1, revoked_at = %s, session_version = session_version + 1 WHERE is_revoked = 0",
				$now
			)
		);

		if ( is_array( $user_ids ) ) {
			foreach ( $user_ids as $uid ) {
				$uid = absint( $uid );
				if ( $uid > 0 ) {
					\WP_Session_Tokens::get_instance( $uid )->destroy_all();
				}
			}
		}

		if ( is_user_logged_in() && ! empty( $_COOKIE[ self::SESSION_COOKIE_NAME ] ) ) {
			setcookie(
				self::SESSION_COOKIE_NAME,
				'',
				time() - YEAR_IN_SECONDS,
				COOKIEPATH,
				COOKIE_DOMAIN,
				is_ssl(),
				true
			);
			unset( $_COOKIE[ self::SESSION_COOKIE_NAME ] );
			wp_logout();
		}
	}

	/**
	 * Whether the current HTTP request includes a temporary-login token query arg.
	 *
	 * Other modules should use: apply_filters( 'wpps_tl_is_token_login_request', false )
	 *
	 * @param bool $is Prior value from other callbacks.
	 * @return bool
	 */
	public function filterIsTokenLoginRequest( bool $is = false ): bool {
		if ( $is ) {
			return true;
		}
		return self::requestHasTokenParam();
	}

	/**
	 * @return bool True when {@see self::TOKEN_PARAM} is present and non-empty.
	 */
	public static function requestHasTokenParam(): bool {
		if ( ! isset( $_GET[ self::TOKEN_PARAM ] ) ) {
			return false;
		}
		$token = sanitize_text_field( wp_unslash( $_GET[ self::TOKEN_PARAM ] ) );
		return $token !== '';
	}

	/**
	 * Register hooks for an authenticated temporary session (skipped for normal users).
	 *
	 * @return void
	 */
	public function maybeRegisterSessionHooks(): void {
		if ( ! is_user_logged_in() ) {
			return;
		}

		$user_id = get_current_user_id();
		if ( ! $this->hasTempSessionMeta( $user_id ) ) {
			return;
		}

		$this->registerSessionEnforcementHooks();
	}

	/**
	 * Register capability enforcement and admin restrictions for an active temporary session.
	 *
	 * Called on normal requests (init) and immediately when a token login establishes a session
	 * so role caps apply before redirect on the same request.
	 *
	 * @return void
	 */
	private function registerSessionEnforcementHooks(): void {
		static $registered = false;
		if ( $registered ) {
			return;
		}
		$registered = true;

		$this->ensureDatabaseTables();

		add_action( 'init', [ $this, 'checkExpiredLogins' ], 2 );
		add_action( 'admin_init', [ $this, 'blockPowersuiteAccess' ], 1 );
		add_action( 'admin_init', [ $this, 'blockPowersuitePluginTampering' ], 1 );
		add_action( 'admin_init', [ $this, 'blockTemporaryUserAdminActions' ], 2 );
		add_filter( 'rest_pre_dispatch', [ $this, 'blockTemporaryUserRestRequests' ], 10, 3 );
		add_filter( 'user_has_cap', [ $this, 'filterTemporarySessionCapabilities' ], 10, 4 );
		add_action( 'admin_bar_menu', [ $this, 'addAdminBarIndicator' ], 999 );
		add_action( 'wp_head', [ $this, 'addAdminBarStyles' ] );
		add_action( 'admin_head', [ $this, 'addAdminBarStyles' ] );
	}

	/**
	 * Single admin-ajax entry point (replaces ten separate wp_ajax_tl_* handlers).
	 */
	private function registerAdminAjaxHandlers(): void {
		add_action( 'wp_ajax_tl_admin', [ $this, 'ajaxAdminRouter' ] );
	}

	/**
	 * Route Temporary Login admin AJAX by tl_op (or legacy action=tl_* for exports/bookmarks).
	 */
	public function ajaxAdminRouter(): void {
		$op = isset( $_REQUEST['tl_op'] ) ? sanitize_key( wp_unslash( (string) $_REQUEST['tl_op'] ) ) : '';

		if ( $op === '' && isset( $_REQUEST['action'] ) ) {
			$legacy = sanitize_key( wp_unslash( (string) $_REQUEST['action'] ) );
			if ( str_starts_with( $legacy, 'tl_' ) && $legacy !== 'tl_admin' ) {
				$op = substr( $legacy, 3 );
			}
		}

		if ( $op !== '' ) {
			$this->ensureDatabaseTables();
		}

		match ( $op ) {
			'create_login'    => $this->ajaxCreateLogin(),
			'revoke_login'    => $this->ajaxRevokeLogin(),
			'enable_login'    => $this->ajaxEnableLogin(),
			'delete_login'    => $this->ajaxDeleteLogin(),
			'update_login'    => $this->ajaxUpdateLogin(),
			'get_login'       => $this->ajaxGetLogin(),
			'export_logs'     => $this->ajaxExportLogs(),
			'get_logs'        => $this->ajaxGetLogs(),
			'search_users'    => $this->ajaxSearchUsers(),
			'issue_copy_link' => $this->ajaxIssueCopyLink(),
			default           => wp_send_json_error(
				[ 'message' => __( 'Unknown Temporary Login action.', 'wp-powersuite' ) ],
				400
			),
		};
	}

	/**
	 * Enqueue admin CSS/JS only on the Temporary Login manager screen.
	 *
	 * @param string $hook_suffix Current admin page hook.
	 * @return void
	 */
	public function enqueueAdminAssets( string $hook_suffix ): void {
		$allowed_hooks = [
			'wp-powersuite_page_powersuite-temporary-login',
			'powersuite_page_powersuite-temporary-login',
		];
		if ( ! in_array( $hook_suffix, $allowed_hooks, true ) ) {
			return;
		}

		if ( ! wp_style_is( 'wp-powersuite-admin', 'registered' ) && defined( 'WP_POWERSUITE_URL' ) ) {
			wp_register_style(
				'wp-powersuite-admin',
				WP_POWERSUITE_URL . 'src/Admin/Assets/app.css',
				[ 'wp-admin' ],
				defined( 'WP_POWERSUITE_VERSION' ) ? WP_POWERSUITE_VERSION : self::MODULE_VERSION
			);
		}
		if ( wp_style_is( 'wp-powersuite-admin', 'registered' ) ) {
			wp_enqueue_style( 'wp-powersuite-admin' );
		}

		wp_enqueue_style(
			'wpps-temporary-login-admin',
			$this->getAssetUrl( 'temporary-login-admin.css' ),
			wp_style_is( 'wp-powersuite-admin', 'registered' ) ? [ 'wp-powersuite-admin' ] : [],
			self::MODULE_VERSION
		);
		wp_enqueue_script(
			'wpps-temporary-login-admin',
			$this->getAssetUrl( 'temporary-login-admin.js' ),
			[ 'jquery' ],
			self::MODULE_VERSION,
			true
		);

		wp_localize_script(
			'wpps-temporary-login-admin',
			'wppsTemporaryLogin',
			[
				'ajaxUrl'           => admin_url( 'admin-ajax.php' ),
				'homeUrl'           => home_url( '/' ),
				'tokenKey'          => self::TOKEN_PARAM,
				'nonce'             => wp_create_nonce( 'tl_nonce' ),
				'premiumUnlocked'   => FeatureGate::isPremiumLicensed(),
				'freeExpiryType'    => FeatureGate::FREE_EXPIRY_TYPE,
				'licenseUrl'        => admin_url( 'admin.php?page=powersuite-license' ),
				'strings'  => [
					'createTitle'       => __( 'Create Temporary Login', 'wp-powersuite' ),
					'editTitle'         => __( 'Edit Temporary Login', 'wp-powersuite' ),
					'createBtn'         => __( 'Create Login', 'wp-powersuite' ),
					'updateBtn'         => __( 'Update Login', 'wp-powersuite' ),
					'creating'          => __( 'Creating…', 'wp-powersuite' ),
					'updating'          => __( 'Updating…', 'wp-powersuite' ),
					'createdSuccess'    => __( 'Temporary login has been created successfully.', 'wp-powersuite' ),
					'genericError'      => __( 'An error occurred.', 'wp-powersuite' ),
					'requestFailed'     => __( 'The request failed. Please try again.', 'wp-powersuite' ),
					'searchFailed'      => __( 'User search failed. Please try again.', 'wp-powersuite' ),
					'handlerMissing'    => __( 'Temporary Login is not responding. Reload the page or clear WP PowerSuite cache, then try again.', 'wp-powersuite' ),
					'copyFallback'      => __( 'Copy the link below.', 'wp-powersuite' ),
					'copied'            => __( 'Copied', 'wp-powersuite' ),
					'copiedExclaim'     => __( 'Copied!', 'wp-powersuite' ),
					'confirmRevoke'     => __( 'Are you sure you want to revoke this login? Active sessions will be ended.', 'wp-powersuite' ),
					'confirmEnable'     => __( 'Are you sure you want to re-enable this login?', 'wp-powersuite' ),
					'confirmDelete'     => __( 'Are you sure you want to permanently delete this login? This action cannot be undone.', 'wp-powersuite' ),
					'confirmNewLink'    => __( 'Generate a new link? The previous URL will stop working immediately.', 'wp-powersuite' ),
					'revokeFailed'      => __( 'Failed to revoke login.', 'wp-powersuite' ),
					'enableFailed'      => __( 'Failed to enable login.', 'wp-powersuite' ),
					'deleteFailed'      => __( 'Failed to delete login.', 'wp-powersuite' ),
					'copyLinkFailed'    => __( 'Could not generate a login link.', 'wp-powersuite' ),
					'loadingLogs'       => __( 'Loading logs...', 'wp-powersuite' ),
					'logsUnused'        => __( 'This login link has not been used yet.', 'wp-powersuite' ),
					'logsLoadFailed'    => __( 'Failed to load logs.', 'wp-powersuite' ),
					'logsError'         => __( 'An error occurred while loading logs.', 'wp-powersuite' ),
					'searchPlaceholder' => __( 'Search users by name, login, or email…', 'wp-powersuite' ),
					'searching'         => __( 'Searching…', 'wp-powersuite' ),
					'noUsers'           => __( 'No users found.', 'wp-powersuite' ),
					'colTime'           => __( 'Time', 'wp-powersuite' ),
					'colAction'         => __( 'Action', 'wp-powersuite' ),
					'colIp'             => __( 'IP Address', 'wp-powersuite' ),
					'colUa'             => __( 'User Agent', 'wp-powersuite' ),
					'colPage'           => __( 'Page', 'wp-powersuite' ),
				],
			]
		);
	}

	/**
	 * @param string $file Filename under assets/.
	 * @return string
	 */
	private function getAssetUrl( string $file ): string {
		return plugins_url( 'assets/' . $file, __FILE__ );
	}

	/**
	 * Add Temporary Login submenu under WP PowerSuite (dedicated page like Admin Menu Organizer).
	 *
	 * @since 1.0.0
	 * @return void
	 */
	public function addAdminMenu(): void {
		add_submenu_page(
			'powersuite',
			__( 'Temporary Login', 'wp-powersuite' ),
			__( 'Temporary Login', 'wp-powersuite' ),
			'manage_options',
			'powersuite-temporary-login',
			[ $this, 'renderTemporaryLoginPage' ]
		);
	}

	/**
	 * Render the Temporary Login admin page (full page, not modal).
	 *
	 * @since 1.0.0
	 * @return void
	 */
	public function renderTemporaryLoginPage(): void {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'You do not have sufficient permissions to access this page.', 'wp-powersuite' ) );
		}

		$this->ensureDatabaseTables();

		if ( ! $this->tablesExist() ) {
			wp_die(
				esc_html__( 'Temporary Login could not create its database tables. Ask your host to grant CREATE TABLE permission for this site, then reload this page.', 'wp-powersuite' ),
				esc_html__( 'Database setup required', 'wp-powersuite' ),
				[ 'response' => 500 ]
			);
		}

		$module_id = self::MODULE_ID;
		$module_meta = [ '_directory' => __DIR__ ];
		include __DIR__ . '/admin.php';
	}

	/**
	 * Create database tables if missing (safe to call when the module is enabled).
	 *
	 * @return void
	 */
	public function setupDatabase(): void {
		$this->ensureDatabaseTables();
	}

	/**
	 * Ensure custom tables exist. The ready option is a cache only — tables are always verified.
	 *
	 * @return void
	 */
	private function ensureDatabaseTables(): void {
		if ( $this->tablesExist() ) {
			$this->upgradeSchema();
			if ( get_option( self::DB_READY_OPTION, '' ) !== '1' ) {
				update_option( self::DB_READY_OPTION, '1', false );
			}
			return;
		}

		delete_option( self::DB_READY_OPTION );
		$this->createTables();

		if ( $this->tablesExist() ) {
			update_option( self::DB_READY_OPTION, '1', false );
		}
	}

	/**
	 * Apply incremental schema changes via dbDelta (new installs and upgrades).
	 */
	private function upgradeSchema(): void {
		$this->createTables();
		$this->ensureSchemaColumns();
	}

	/**
	 * dbDelta can miss new columns on existing installs — verify with ALTER TABLE fallback.
	 */
	private function ensureSchemaColumns(): void {
		global $wpdb;

		$table = $wpdb->prefix . self::DB_TABLE_NAME;
		if ( $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $table ) ) !== $table ) {
			return;
		}

		$columns = $wpdb->get_col( "SHOW COLUMNS FROM {$table}", 0 );
		if ( ! is_array( $columns ) ) {
			return;
		}

		if ( ! in_array( 'bind_user_agent', $columns, true ) ) {
			$wpdb->query( "ALTER TABLE {$table} ADD COLUMN bind_user_agent tinyint(1) NOT NULL DEFAULT 0" );
		}

		if ( ! in_array( 'session_version', $columns, true ) ) {
			$wpdb->query( "ALTER TABLE {$table} ADD COLUMN session_version int(11) UNSIGNED NOT NULL DEFAULT 0" );
		}
	}

	/**
	 * @return bool True when both tl_temporary_logins and tl_activity_logs exist.
	 */
	private function tablesExist(): bool {
		global $wpdb;

		$main_table = $wpdb->prefix . self::DB_TABLE_NAME;
		$log_table  = $wpdb->prefix . self::DB_LOG_TABLE_NAME;

		$found_main = $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $main_table ) );
		$found_log  = $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $log_table ) );

		return $found_main === $main_table && $found_log === $log_table;
	}

	/**
	 * Create Database Tables
	 *
	 * Creates custom tables for storing temporary logins and activity logs.
	 *
	 * @since 1.0.0
	 * @return void
	 */
	private function createTables(): void {
		global $wpdb;

		$charset_collate = $wpdb->get_charset_collate();
		$table_name = $wpdb->prefix . self::DB_TABLE_NAME;
		$log_table_name = $wpdb->prefix . self::DB_LOG_TABLE_NAME;

		// Temporary logins table
		$sql = "CREATE TABLE IF NOT EXISTS $table_name (
			id bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
			token varchar(255) NOT NULL,
			user_id bigint(20) UNSIGNED NOT NULL,
			created_by bigint(20) UNSIGNED NOT NULL,
			created_at datetime NOT NULL,
			expires_at datetime NOT NULL,
			single_use tinyint(1) DEFAULT 0,
			used_count int(11) DEFAULT 0,
			max_uses int(11) DEFAULT 0,
			role varchar(50) DEFAULT 'subscriber',
			allowed_capabilities text,
			ip_restriction varchar(255) DEFAULT NULL,
			user_agent_hash varchar(64) DEFAULT NULL,
			is_revoked tinyint(1) DEFAULT 0,
			revoked_at datetime DEFAULT NULL,
			revoked_by bigint(20) UNSIGNED DEFAULT NULL,
			redirect_to varchar(500) DEFAULT NULL,
			bind_user_agent tinyint(1) DEFAULT 0,
			session_version int(11) UNSIGNED DEFAULT 0,
			PRIMARY KEY (id),
			UNIQUE KEY token (token),
			KEY user_id (user_id),
			KEY expires_at (expires_at),
			KEY is_revoked (is_revoked)
		) $charset_collate;";

		// Activity logs table
		$log_sql = "CREATE TABLE IF NOT EXISTS $log_table_name (
			id bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
			login_id bigint(20) UNSIGNED NOT NULL,
			user_id bigint(20) UNSIGNED NOT NULL,
			action varchar(50) NOT NULL,
			ip_address varchar(45) NOT NULL,
			user_agent text,
			page_accessed varchar(500) DEFAULT NULL,
			logged_at datetime NOT NULL,
			PRIMARY KEY (id),
			KEY login_id (login_id),
			KEY user_id (user_id),
			KEY logged_at (logged_at)
		) $charset_collate;";

		require_once ABSPATH . 'wp-admin/includes/upgrade.php';
		dbDelta( $sql );
		dbDelta( $log_sql );

		// dbDelta can fail silently on some hosts; direct CREATE is a fallback.
		if ( ! $this->tablesExist() ) {
			$wpdb->query( $sql );
			$wpdb->query( $log_sql );
		}
	}

	/**
	 * Handle Temporary Login
	 *
	 * Processes temporary login token and authenticates user. The user visits a URL
	 * with the token (e.g. ?tl_token=xxx); no login form or captcha is shown. The
	 * token acts as the secret, so login-form captchas do not apply. Use expiry,
	 * single-use, or IP restrictions to limit link abuse.
	 *
	 * @since 1.0.0
	 * @return void
	 */
	public function handleTemporaryLogin(): void {
		if ( ! isset( $_GET[ self::TOKEN_PARAM ] ) ) {
			return;
		}

		$this->ensureDatabaseTables();

		if ( ! $this->allowTokenAttemptFromIp() ) {
			wp_die(
				esc_html__( 'Too many login attempts. Please try again in a few minutes.', 'wp-powersuite' ),
				esc_html__( 'Too Many Requests', 'wp-powersuite' ),
				[ 'response' => 429 ]
			);
		}

		$token = sanitize_text_field( wp_unslash( $_GET[ self::TOKEN_PARAM ] ) );

		if ( $token === '' ) {
			$this->bumpTokenFailure();
			wp_die( esc_html__( 'Invalid login token.', 'wp-powersuite' ), esc_html__( 'Authentication Error', 'wp-powersuite' ), [ 'response' => 403 ] );
		}

		$login = $this->getLoginByToken( $token );

		if ( ! $login ) {
			$this->bumpTokenFailure();
			wp_die( esc_html__( 'Invalid or expired login token.', 'wp-powersuite' ), esc_html__( 'Authentication Error', 'wp-powersuite' ), [ 'response' => 403 ] );
		}

		if ( $login->is_revoked ) {
			$this->bumpTokenFailure();
			$this->logActivity( $login->id, $login->user_id, 'login_denied_revoked', $this->getClientIp(), $this->getUserAgent() );
			wp_die( esc_html__( 'This login link has been revoked.', 'wp-powersuite' ), esc_html__( 'Access Denied', 'wp-powersuite' ), [ 'response' => 403 ] );
		}

		if ( $this->isExpired( $login ) ) {
			$this->bumpTokenFailure();
			$this->logActivity( $login->id, $login->user_id, 'login_denied_expired', $this->getClientIp(), $this->getUserAgent() );
			wp_die( esc_html__( 'This login link has expired.', 'wp-powersuite' ), esc_html__( 'Access Denied', 'wp-powersuite' ), [ 'response' => 403 ] );
		}

		if ( $login->single_use && $login->used_count > 0 ) {
			$this->bumpTokenFailure();
			$this->logActivity( $login->id, $login->user_id, 'login_denied_used', $this->getClientIp(), $this->getUserAgent() );
			wp_die( esc_html__( 'This login link has already been used.', 'wp-powersuite' ), esc_html__( 'Access Denied', 'wp-powersuite' ), [ 'response' => 403 ] );
		}

		if ( $login->max_uses > 0 && $login->used_count >= $login->max_uses ) {
			$this->bumpTokenFailure();
			$this->logActivity( $login->id, $login->user_id, 'login_denied_max_uses', $this->getClientIp(), $this->getUserAgent() );
			wp_die( esc_html__( 'Maximum login attempts reached for this link.', 'wp-powersuite' ), esc_html__( 'Access Denied', 'wp-powersuite' ), [ 'response' => 403 ] );
		}

		if ( ! empty( $login->ip_restriction ) && ! $this->checkIpRestriction( $login->ip_restriction, $this->getIpForRestrictionCheck() ) ) {
			$this->bumpTokenFailure();
			$this->logActivity( $login->id, $login->user_id, 'login_denied_ip', $this->getClientIp(), $this->getUserAgent() );
			wp_die( esc_html__( 'Access denied from this IP address.', 'wp-powersuite' ), esc_html__( 'Access Denied', 'wp-powersuite' ), [ 'response' => 403 ] );
		}

		// Check user-agent binding (on first use sets hash; thereafter enforces match).
		$bind_ua = ! empty( $login->bind_user_agent ) || ! empty( $login->user_agent_hash );
		if ( $bind_ua ) {
			$current_ua_hash = hash( 'sha256', $this->getUserAgent() );
			if ( empty( $login->user_agent_hash ) ) {
				$this->updateLoginUserAgent( $login->id, $current_ua_hash );
			} elseif ( $login->user_agent_hash !== $current_ua_hash ) {
				$this->bumpTokenFailure();
				$this->logActivity( $login->id, $login->user_id, 'login_denied_user_agent', $this->getClientIp(), $this->getUserAgent() );
				wp_die( esc_html__( 'Access denied: device mismatch.', 'wp-powersuite' ), esc_html__( 'Access Denied', 'wp-powersuite' ), [ 'response' => 403 ] );
			}
		}

		$user = get_userdata( $login->user_id );
		if ( ! $user ) {
			$this->bumpTokenFailure();
			wp_die( esc_html__( 'User not found.', 'wp-powersuite' ), esc_html__( 'Authentication Error', 'wp-powersuite' ), [ 'response' => 403 ] );
		}

		// Logout current user if different
		if ( is_user_logged_in() && get_current_user_id() !== $login->user_id ) {
			wp_logout();
		}

		$already_same_user = is_user_logged_in() && get_current_user_id() === $login->user_id;

		if ( ! $already_same_user ) {
			wp_set_current_user( $login->user_id );
			wp_set_auth_cookie( $login->user_id, false );

			/** This action is documented in wp-includes/user.php */
			do_action( 'wp_login', $user->user_login, $user );
		}

		$this->establishTemporarySession( $login );

		$this->incrementLoginUseCount( $login->id );

		$this->logActivity( $login->id, $login->user_id, 'login_success', $this->getClientIp(), $this->getUserAgent(), $this->getCurrentPage() );

		$this->clearTokenRateLimitForIp();

		$this->maybeNotifyAdminLoginUsed( $login, $user );

		do_action( 'tl_after_login_success', $login->id, $login->user_id );

		$this->redirectAfterLogin( $login );
	}

	/**
	 * Block sensitive WP PowerSuite admin pages for temporary sessions.
	 *
	 * Allows the module list and module custom pages; blocks settings, licensing,
	 * performance monitor, and temporary login management.
	 *
	 * @since 1.0.0
	 * @return void
	 */
	public function blockPowersuiteAccess(): void {
		if ( ! is_admin() || ! is_user_logged_in() ) {
			return;
		}

		$user_id = get_current_user_id();
		if ( ! $this->hasTempSessionMeta( $user_id ) ) {
			return;
		}

		$had_temp_session = true;
		$login            = $this->getActiveSessionLogin( $user_id );

		if ( ! $login ) {
			$this->forceEndTemporarySession( $had_temp_session );
			return;
		}

		$current_page = isset( $_GET['page'] ) ? sanitize_text_field( wp_unslash( $_GET['page'] ) ) : '';
		if ( $current_page === '' || ! in_array( $current_page, self::BLOCKED_POWERSUITE_PAGES, true ) ) {
			return;
		}

		$this->logActivity( $login->id, $user_id, 'access_denied_powersuite', $this->getClientIp(), $this->getUserAgent(), $current_page );
		wp_die(
			esc_html__( 'Temporary login users cannot access WP PowerSuite settings, licensing, performance tools, or temporary login management.', 'wp-powersuite' ),
			esc_html__( 'Access Denied', 'wp-powersuite' ),
			[ 'response' => 403 ]
		);
	}

	/**
	 * Block temporary users from editing/deleting any admin or super admin, and from adding any user.
	 *
	 * @since 1.0.0
	 * @return void
	 */
	public function blockTemporaryUserAdminActions(): void {
		if ( ! is_admin() || ! is_user_logged_in() ) {
			return;
		}

		$user_id = get_current_user_id();
		if ( ! $this->hasTempSessionMeta( $user_id ) ) {
			return;
		}

		$login = $this->getActiveSessionLogin( $user_id );
		if ( ! $login ) {
			return;
		}

		$script_name = basename( $_SERVER['SCRIPT_NAME'] ?? '' );

		if ( in_array( $script_name, self::ALWAYS_BLOCKED_ADMIN_SCREENS, true ) ) {
			$this->denyTemporaryAdminAccess( $login, $user_id, 'access_denied_screen', $script_name );
		}

		$this->blockTemporaryUserAccountActions( $login, $user_id, $script_name );
		$this->blockTemporaryPluginThemeScreens( $login, $user_id, $script_name );
		$this->blockTemporaryPluginThemeRequests( $login, $user_id, $script_name );
	}

	/**
	 * Block REST mutations that mirror admin_init restrictions for temporary sessions.
	 *
	 * @param mixed            $result  Response to replace.
	 * @param \WP_REST_Server  $server  REST server instance.
	 * @param \WP_REST_Request $request Request object.
	 * @return mixed
	 */
	public function blockTemporaryUserRestRequests( $result, $server, $request ) {
		unset( $server );

		if ( ! is_user_logged_in() ) {
			return $result;
		}

		$user_id = get_current_user_id();
		if ( ! $this->hasTempSessionMeta( $user_id ) ) {
			return $result;
		}

		$login = $this->getActiveSessionLogin( $user_id );
		if ( ! $login ) {
			return $result;
		}

		if ( ! $request instanceof \WP_REST_Request ) {
			return $result;
		}

		$method = strtoupper( $request->get_method() );
		if ( ! in_array( $method, [ 'POST', 'PUT', 'PATCH', 'DELETE' ], true ) ) {
			return $result;
		}

		$route = (string) $request->get_route();

		if ( preg_match( '#^/wp/v2/users(?:/|\?|$)#', $route ) ) {
			return $this->restAccessDenied( $login, $user_id, 'access_denied_create_user' );
		}

		$params = $request->get_json_params();
		if ( is_array( $params ) ) {
			$roles = $params['roles'] ?? null;
			if ( is_array( $roles ) && in_array( 'administrator', $roles, true ) ) {
				return $this->restAccessDenied( $login, $user_id, 'access_denied_create_admin' );
			}
			if ( isset( $params['role'] ) && sanitize_text_field( (string) $params['role'] ) === 'administrator' ) {
				return $this->restAccessDenied( $login, $user_id, 'access_denied_create_admin' );
			}
		}

		if ( preg_match( '#^/wp/v2/plugins#', $route ) ) {
			$can_plugins = $this->loginAllows( $login, self::PERM_INSTALL_PLUGINS ) || $this->loginAllows( $login, self::PERM_DELETE_PLUGINS );
			if ( ! $can_plugins ) {
				return $this->restAccessDenied( $login, $user_id, 'access_denied_plugin_install' );
			}
		}

		if ( preg_match( '#^/wp/v2/themes#', $route ) ) {
			$can_themes = $this->loginAllows( $login, self::PERM_INSTALL_THEMES ) || $this->loginAllows( $login, self::PERM_DELETE_THEMES );
			if ( ! $can_themes ) {
				return $this->restAccessDenied( $login, $user_id, 'access_denied_theme_install' );
			}
		}

		return $result;
	}

	/**
	 * @return \WP_Error
	 */
	private function restAccessDenied( object $login, int $user_id, string $log_action ): \WP_Error {
		$this->logActivity( $login->id, $user_id, $log_action, $this->getClientIp(), $this->getUserAgent() );

		$messages = $this->getTemporaryAccessDeniedMessages();

		return new \WP_Error(
			'tl_forbidden',
			$messages[ $log_action ] ?? $messages['access_denied_screen'],
			[ 'status' => 403 ]
		);
	}

	/**
	 * @return array<string, string>
	 */
	private function getTemporaryAccessDeniedMessages(): array {
		return [
			'access_denied_screen'            => __( 'Temporary login users cannot access this admin area.', 'wp-powersuite' ),
			'access_denied_edit_own'          => __( 'Temporary login users cannot edit their own account.', 'wp-powersuite' ),
			'access_denied_add_user'          => __( 'Temporary login users cannot add new users.', 'wp-powersuite' ),
			'access_denied_create_user'       => __( 'Temporary login users cannot add new users.', 'wp-powersuite' ),
			'access_denied_create_admin'      => __( 'Temporary login users cannot create or promote administrator accounts.', 'wp-powersuite' ),
			'access_denied_edit_admin'        => __( 'Temporary login users cannot edit administrator or super admin accounts.', 'wp-powersuite' ),
			'access_denied_delete_admin'      => __( 'Temporary login users cannot delete administrator or super admin accounts.', 'wp-powersuite' ),
			'access_denied_powersuite_plugin' => __( 'Temporary login users cannot deactivate or remove WP PowerSuite.', 'wp-powersuite' ),
			'access_denied_plugin_install'    => __( 'This temporary login does not allow installing or activating plugins.', 'wp-powersuite' ),
			'access_denied_plugin_delete'     => __( 'This temporary login does not allow deactivating or deleting plugins.', 'wp-powersuite' ),
			'access_denied_theme_install'     => __( 'This temporary login does not allow installing or activating themes.', 'wp-powersuite' ),
			'access_denied_theme_delete'      => __( 'This temporary login does not allow deleting themes.', 'wp-powersuite' ),
		];
	}

	/**
	 * @param string[] $columns Users list columns.
	 * @return string[]
	 */
	public function addUsersListColumn( array $columns ): array {
		$columns['wpps_tl_account'] = __( 'Temp access', 'wp-powersuite' );
		return $columns;
	}

	/**
	 * @param string $output      Custom column output.
	 * @param string $column_name Column key.
	 * @param int    $user_id     User ID.
	 * @return string
	 */
	public function renderUsersListColumn( string $output, string $column_name, int $user_id ): string {
		if ( $column_name !== 'wpps_tl_account' ) {
			return $output;
		}

		if ( get_user_meta( $user_id, self::USER_META_PASSWORDLESS_ACCOUNT, true ) === '1' ) {
			return '<span class="wpps-tl-user-badge" style="display:inline-block;padding:2px 6px;border-radius:3px;background:#fcf0f1;color:#8a2424;font-size:11px;font-weight:600;">'
				. esc_html__( 'Link-only', 'wp-powersuite' )
				. '</span>';
		}

		return '—';
	}

	/**
	 * Never allow temporary sessions to deactivate or delete WP PowerSuite.
	 *
	 * @return void
	 */
	public function blockPowersuitePluginTampering(): void {
		if ( ! is_admin() || ! is_user_logged_in() ) {
			return;
		}

		$user_id = get_current_user_id();
		if ( ! $this->hasTempSessionMeta( $user_id ) ) {
			return;
		}

		$login = $this->getActiveSessionLogin( $user_id );
		if ( ! $login ) {
			return;
		}

		if ( ! defined( 'WP_POWERSUITE_PLUGIN_BASENAME' ) ) {
			return;
		}

		$basename = WP_POWERSUITE_PLUGIN_BASENAME;
		$touches_powersuite = false;

		if ( isset( $_REQUEST['plugin'] ) ) {
			$plugin = sanitize_text_field( wp_unslash( $_REQUEST['plugin'] ) );
			if ( $plugin === $basename ) {
				$touches_powersuite = true;
			}
		}

		if ( ! $touches_powersuite && isset( $_REQUEST['checked'] ) && is_array( $_REQUEST['checked'] ) ) {
			$checked = array_map( 'sanitize_text_field', wp_unslash( $_REQUEST['checked'] ) );
			if ( in_array( $basename, $checked, true ) ) {
				$touches_powersuite = true;
			}
		}

		if ( ! $touches_powersuite ) {
			return;
		}

		$action = isset( $_REQUEST['action'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['action'] ) ) : '';
		$action2 = isset( $_REQUEST['action2'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['action2'] ) ) : '';
		$blocked_actions = [
			'deactivate',
			'deactivate-selected',
			'delete-selected',
			'delete-plugin',
		];

		if ( in_array( $action, $blocked_actions, true ) || in_array( $action2, $blocked_actions, true ) ) {
			$this->denyTemporaryAdminAccess( $login, $user_id, 'access_denied_powersuite_plugin' );
		}
	}

	/**
	 * Profile, user create/edit/delete, and administrator promotion rules.
	 *
	 * @param object $login       Active login row.
	 * @param int    $user_id     Current user ID.
	 * @param string $script_name Current admin script basename.
	 * @return void
	 */
	private function blockTemporaryUserAccountActions( object $login, int $user_id, string $script_name ): void {
		if ( $script_name === 'profile.php' ) {
			$this->denyTemporaryAdminAccess( $login, $user_id, 'access_denied_edit_own' );
		}

		if ( $script_name === 'user-new.php' ) {
			$this->denyTemporaryAdminAccess( $login, $user_id, 'access_denied_add_user' );
		}

		if ( isset( $_POST['action'] ) && sanitize_text_field( wp_unslash( $_POST['action'] ) ) === 'createuser' ) {
			$this->denyTemporaryAdminAccess( $login, $user_id, 'access_denied_create_user' );
		}

		$this->blockTemporaryAdministratorPromotion( $login, $user_id );

		$edit_user_id = 0;
		if ( isset( $_GET['user_id'] ) ) {
			$edit_user_id = absint( $_GET['user_id'] );
		} elseif ( isset( $_POST['user_id'] ) ) {
			$edit_user_id = absint( $_POST['user_id'] );
		}

		if ( $script_name === 'user-edit.php' && $edit_user_id > 0 ) {
			if ( $edit_user_id === $user_id ) {
				$this->denyTemporaryAdminAccess( $login, $user_id, 'access_denied_edit_own' );
			}
			$edit_user = get_userdata( $edit_user_id );
			if ( $edit_user && $this->userIsPrivilegedAdmin( $edit_user ) ) {
				$this->denyTemporaryAdminAccess( $login, $user_id, 'access_denied_edit_admin' );
			}
		}

		$this->blockTemporaryAdministratorDeletion( $login, $user_id );
	}

	/**
	 * Plugin/theme list and install screens (allowed only when enabled on the login row).
	 *
	 * @param object $login       Active login row.
	 * @param int    $user_id     Current user ID.
	 * @param string $script_name Current admin script basename.
	 * @return void
	 */
	private function blockTemporaryPluginThemeScreens( object $login, int $user_id, string $script_name ): void {
		$can_plugins = $this->loginAllows( $login, self::PERM_INSTALL_PLUGINS ) || $this->loginAllows( $login, self::PERM_DELETE_PLUGINS );
		$can_themes  = $this->loginAllows( $login, self::PERM_INSTALL_THEMES ) || $this->loginAllows( $login, self::PERM_DELETE_THEMES );

		if ( $script_name === 'plugins.php' && ! $can_plugins ) {
			$this->denyTemporaryAdminAccess( $login, $user_id, 'access_denied_screen', $script_name );
		}

		if ( $script_name === 'plugin-install.php' && ! $this->loginAllows( $login, self::PERM_INSTALL_PLUGINS ) ) {
			$this->denyTemporaryAdminAccess( $login, $user_id, 'access_denied_screen', $script_name );
		}

		if ( $script_name === 'themes.php' && ! $can_themes ) {
			$this->denyTemporaryAdminAccess( $login, $user_id, 'access_denied_screen', $script_name );
		}

		if ( $script_name === 'theme-install.php' && ! $this->loginAllows( $login, self::PERM_INSTALL_THEMES ) ) {
			$this->denyTemporaryAdminAccess( $login, $user_id, 'access_denied_screen', $script_name );
		}
	}

	/**
	 * Block plugin/theme POST actions when the login row did not grant that permission.
	 *
	 * @param object $login       Active login row.
	 * @param int    $user_id     Current user ID.
	 * @param string $script_name Current admin script basename.
	 * @return void
	 */
	private function blockTemporaryPluginThemeRequests( object $login, int $user_id, string $script_name ): void {
		if ( $script_name !== 'plugins.php' && $script_name !== 'themes.php' ) {
			return;
		}

		$action  = isset( $_REQUEST['action'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['action'] ) ) : '';
		$action2 = isset( $_REQUEST['action2'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['action2'] ) ) : '';
		$action  = $action !== '' && $action !== '-1' ? $action : $action2;

		if ( $action === '' || $action === '-1' ) {
			return;
		}

		$install_plugin_actions = [ 'install-plugin', 'upload-plugin', 'activate', 'activate-selected' ];
		$delete_plugin_actions  = [ 'delete-selected', 'deactivate', 'deactivate-selected' ];
		$install_theme_actions  = [ 'install-theme', 'upload-theme', 'activate', 'activate-selected' ];
		$delete_theme_actions   = [ 'delete', 'delete-selected' ];

		if ( $script_name === 'plugins.php' ) {
			if ( in_array( $action, $install_plugin_actions, true ) && ! $this->loginAllows( $login, self::PERM_INSTALL_PLUGINS ) ) {
				$this->denyTemporaryAdminAccess( $login, $user_id, 'access_denied_plugin_install' );
			}
			if ( in_array( $action, $delete_plugin_actions, true ) && ! $this->loginAllows( $login, self::PERM_DELETE_PLUGINS ) ) {
				$this->denyTemporaryAdminAccess( $login, $user_id, 'access_denied_plugin_delete' );
			}
		}

		if ( $script_name === 'themes.php' ) {
			if ( in_array( $action, $install_theme_actions, true ) && ! $this->loginAllows( $login, self::PERM_INSTALL_THEMES ) ) {
				$this->denyTemporaryAdminAccess( $login, $user_id, 'access_denied_theme_install' );
			}
			if ( in_array( $action, $delete_theme_actions, true ) && ! $this->loginAllows( $login, self::PERM_DELETE_THEMES ) ) {
				$this->denyTemporaryAdminAccess( $login, $user_id, 'access_denied_theme_delete' );
			}
		}
	}

	/**
	 * @param object $login Active login row.
	 * @param int    $user_id Current user ID.
	 * @return void
	 */
	private function blockTemporaryAdministratorPromotion( object $login, int $user_id ): void {
		$new_role = '';
		if ( isset( $_POST['role'] ) ) {
			$new_role = sanitize_text_field( wp_unslash( $_POST['role'] ) );
		} elseif ( isset( $_POST['new_role'] ) ) {
			$new_role = sanitize_text_field( wp_unslash( $_POST['new_role'] ) );
		}

		if ( $new_role === 'administrator' ) {
			$this->denyTemporaryAdminAccess( $login, $user_id, 'access_denied_create_admin' );
		}
	}

	/**
	 * @param object $login   Active login row.
	 * @param int    $user_id Current user ID.
	 * @return void
	 */
	private function blockTemporaryAdministratorDeletion( object $login, int $user_id ): void {
		$delete_ids = [];

		if ( isset( $_GET['action'], $_GET['user'] ) && sanitize_text_field( wp_unslash( $_GET['action'] ) ) === 'delete' ) {
			$delete_ids[] = absint( $_GET['user'] );
		}

		if ( isset( $_REQUEST['action'] ) ) {
			$action = sanitize_text_field( wp_unslash( $_REQUEST['action'] ) );
			if ( in_array( $action, [ 'delete', 'delete-selected' ], true ) && isset( $_REQUEST['users'] ) && is_array( $_REQUEST['users'] ) ) {
				$delete_ids = array_merge( $delete_ids, array_map( 'absint', wp_unslash( $_REQUEST['users'] ) ) );
			}
		}

		foreach ( array_filter( $delete_ids ) as $delete_user_id ) {
			$delete_user = get_userdata( $delete_user_id );
			if ( $delete_user && $this->userIsPrivilegedAdmin( $delete_user ) ) {
				$this->denyTemporaryAdminAccess( $login, $user_id, 'access_denied_delete_admin' );
			}
		}
	}

	/**
	 * @param \WP_User $user User object.
	 * @return bool
	 */
	private function userIsPrivilegedAdmin( \WP_User $user ): bool {
		return in_array( 'administrator', $user->roles, true ) || is_super_admin( $user->ID );
	}

	/**
	 * @return array<string, bool>
	 */
	private function getDefaultLoginPermissions(): array {
		return [
			self::PERM_INSTALL_PLUGINS => false,
			self::PERM_DELETE_PLUGINS  => false,
			self::PERM_INSTALL_THEMES  => false,
			self::PERM_DELETE_THEMES   => false,
		];
	}

	/**
	 * @param array<string, mixed> $args Create/update request args.
	 * @return string JSON for allowed_capabilities column.
	 */
	private function encodeLoginPermissionsFromArgs( array $args ): string {
		$perms = $this->getDefaultLoginPermissions();
		foreach ( array_keys( $perms ) as $key ) {
			if ( ! empty( $args[ $key ] ) ) {
				$perms[ $key ] = true;
			}
		}
		return wp_json_encode( $perms ) ?: '{}';
	}

	/**
	 * @param object $login Login row.
	 * @return array<string, bool>
	 */
	private function getLoginPermissions( object $login ): array {
		$perms = $this->getDefaultLoginPermissions();
		if ( empty( $login->allowed_capabilities ) ) {
			return $perms;
		}
		$decoded = json_decode( (string) $login->allowed_capabilities, true );
		if ( ! is_array( $decoded ) ) {
			return $perms;
		}
		foreach ( array_keys( $perms ) as $key ) {
			if ( array_key_exists( $key, $decoded ) ) {
				$perms[ $key ] = (bool) $decoded[ $key ];
			}
		}
		return $perms;
	}

	/**
	 * @param object $login Active login row.
	 * @param string $perm  One of the PERM_* constants.
	 * @return bool
	 */
	private function loginAllows( object $login, string $perm ): bool {
		$perms = $this->getLoginPermissions( $login );
		return ! empty( $perms[ $perm ] );
	}

	/**
	 * @param array<string, mixed> $args Update/create args.
	 * @return bool
	 */
	private function argsIncludePermissionFields( array $args ): bool {
		foreach ( array_keys( $this->getDefaultLoginPermissions() ) as $key ) {
			if ( array_key_exists( $key, $args ) ) {
				return true;
			}
		}
		return false;
	}

	/**
	 * @param object      $login       Active login row.
	 * @param int         $user_id     Current user ID.
	 * @param string      $log_action  Activity log action key.
	 * @param string|null $page        Optional page identifier for the log.
	 * @return void
	 */
	private function denyTemporaryAdminAccess( object $login, int $user_id, string $log_action, ?string $page = null ): void {
		$this->logActivity( $login->id, $user_id, $log_action, $this->getClientIp(), $this->getUserAgent(), $page ?? '' );

		$messages = $this->getTemporaryAccessDeniedMessages();

		wp_die(
			esc_html( $messages[ $log_action ] ?? $messages['access_denied_screen'] ),
			esc_html__( 'Access Denied', 'wp-powersuite' ),
			[ 'response' => 403 ]
		);
	}

	/**
	 * Track Page Access
	 *
	 * Logs page access for temporary users (optional tracking).
	 *
	 * @since 1.0.0
	 * @return void
	 */
	public function trackPageAccess(): void {
		if ( ! is_user_logged_in() ) {
			return;
		}

		$user_id = get_current_user_id();
		if ( ! $this->hasTempSessionMeta( $user_id ) ) {
			return;
		}

		$login = $this->getActiveSessionLogin( $user_id );

		if ( ! $login ) {
			return;
		}

		// Only log page access occasionally to avoid flooding the database
		// Log every 10th page access or important pages
		$should_log = false;
		$current_page = $this->getCurrentPage();
		
		// Always log admin pages
		if ( is_admin() ) {
			$should_log = true;
		} else {
			// Log frontend pages occasionally (every 10th access)
			$last_logged = get_transient( 'tl_last_page_log_' . $login->id );
			if ( ! $last_logged || ( time() - $last_logged ) > 300 ) { // Log at most every 5 minutes
				$should_log = true;
				set_transient( 'tl_last_page_log_' . $login->id, time(), 300 );
			}
		}

		if ( $should_log ) {
			$this->logActivity( $login->id, $user_id, 'page_access', $this->getClientIp(), $this->getUserAgent(), $current_page );
		}
	}

	/**
	 * Check Expired Logins
	 *
	 * Checks if current user's temporary login has expired and logs them out.
	 *
	 * @since 1.0.0
	 * @return void
	 */
	public function checkExpiredLogins(): void {
		if ( ! is_user_logged_in() ) {
			return;
		}

		$user_id = absint( get_current_user_id() );
		$lid     = $this->getSessionLoginIdFromCookie();
		if ( ! $lid ) {
			return;
		}

		$login = $this->getLoginById( $lid );
		if ( ! $login || (int) $login->user_id !== $user_id ) {
			$this->forceEndTemporarySession( true );
			return;
		}

		if ( $login->is_revoked ) {
			$this->logActivity( $login->id, $user_id, 'auto_logout_revoked', $this->getClientIp(), $this->getUserAgent() );
			$this->clearTemporarySession( $user_id );
			wp_logout();
			wp_safe_redirect( home_url() );
			exit;
		}

		if ( $this->isExpired( $login ) ) {
			$this->logActivity( $login->id, $user_id, 'auto_logout_expired', $this->getClientIp(), $this->getUserAgent() );
			$this->clearTemporarySession( $user_id );
			wp_logout();
			wp_safe_redirect( home_url() );
			exit;
		}
	}

	/**
	 * Prevent Password Login
	 *
	 * Prevents passwordless-only accounts (created via email) from using wp-login.
	 *
	 * @since 1.0.0
	 * @param \WP_User|\WP_Error $user User object or error.
	 * @param string             $password Password.
	 * @return \WP_User|\WP_Error User object or error.
	 */
	public function preventPasswordLogin( $user, string $password ) {
		if ( $user instanceof \WP_User && $this->mustUseTemporaryLink( (int) $user->ID ) ) {
			return new \WP_Error(
				'temporary_user',
				__( 'This account can only be accessed via temporary login link.', 'wp-powersuite' )
			);
		}
		return $user;
	}

	/**
	 * Allow 2FA bypass when logging in via a valid temporary login link.
	 *
	 * @since 1.0.0
	 * @param bool     $bypass Whether to bypass 2FA.
	 * @param \WP_User $user   User being authenticated.
	 * @return bool Whether to bypass 2FA.
	 */
	public function allow2FABypassForTemporaryLogin( bool $bypass, \WP_User $user ): bool {
		if ( ! isset( $_GET[ self::TOKEN_PARAM ] ) ) {
			return $bypass;
		}
		$token = sanitize_text_field( wp_unslash( $_GET[ self::TOKEN_PARAM ] ) );
		if ( $token === '' ) {
			return $bypass;
		}
		$login = $this->getLoginByToken( $token );
		if ( ! $login || $login->is_revoked || $this->isExpired( $login ) ) {
			return $bypass;
		}
		// Only bypass when the authenticated user matches the temporary login user
		if ( (int) $login->user_id !== (int) $user->ID ) {
			return $bypass;
		}
		return true;
	}

	/**
	 * Disable Password Reset
	 *
	 * Prevents temporary users from resetting their password.
	 *
	 * @since 1.0.0
	 * @param bool $allow Whether password reset is allowed.
	 * @param int  $user_id User ID.
	 * @return bool Whether password reset is allowed.
	 */
	public function disablePasswordReset( bool $allow, int $user_id ): bool {
		if ( $this->mustUseTemporaryLink( $user_id ) ) {
			return false;
		}
		return $allow;
	}

	/**
	 * Limit capabilities to the role assigned on the temporary login row.
	 *
	 * @param array<string, bool> $allcaps All capabilities for the user.
	 * @param array<int, string>  $caps    Required capabilities.
	 * @param array<int, mixed>   $args    Capability check arguments.
	 * @param \WP_User            $user    User object.
	 * @return array<string, bool>
	 */
	public function filterTemporarySessionCapabilities( array $allcaps, array $caps, array $args, \WP_User $user ): array {
		if ( ! $this->hasTempSessionMeta( (int) $user->ID ) ) {
			return $allcaps;
		}

		$login = $this->getActiveSessionLogin( (int) $user->ID );
		if ( ! $login ) {
			return $allcaps;
		}

		$role_caps = $this->getSessionRoleCapabilities( $login );
		if ( $role_caps === null ) {
			return $allcaps;
		}

		$effective = [];
		foreach ( $role_caps as $cap => $granted ) {
			$effective[ $cap ] = (bool) $granted;
		}

		return $effective;
	}

	/**
	 * @param object $login Active session login row.
	 * @return array<string, bool>|null
	 */
	private function getSessionRoleCapabilities( object $login ): ?array {
		if ( $this->session_role_caps_cache !== null ) {
			return $this->session_role_caps_cache;
		}

		$role_slug = sanitize_text_field( $login->role ?? 'subscriber' );
		$wp_role   = get_role( $role_slug );
		if ( ! $wp_role ) {
			$wp_role = get_role( 'subscriber' );
		}
		if ( ! $wp_role ) {
			return null;
		}

		$caps = $wp_role->capabilities;
		$perms = $this->getLoginPermissions( $login );

		if ( $perms[ self::PERM_INSTALL_PLUGINS ] ) {
			$caps['install_plugins']  = true;
			$caps['activate_plugins'] = true;
			$caps['upload_plugins']   = true;
		}
		if ( $perms[ self::PERM_DELETE_PLUGINS ] ) {
			$caps['delete_plugins']     = true;
			$caps['deactivate_plugins'] = true;
		}
		if ( $perms[ self::PERM_INSTALL_THEMES ] ) {
			$caps['install_themes'] = true;
			$caps['switch_themes']  = true;
			$caps['upload_themes']  = true;
		}
		if ( $perms[ self::PERM_DELETE_THEMES ] ) {
			$caps['delete_themes'] = true;
		}

		// Never grant file editors or core updates during a temporary session.
		foreach ( [ 'edit_plugins', 'edit_themes', 'update_core', 'update_languages', 'install_languages' ] as $forbidden_cap ) {
			$caps[ $forbidden_cap ] = false;
		}

		$this->session_role_caps_cache = $caps;

		return $this->session_role_caps_cache;
	}

	/**
	 * Whether this account must sign in via a temporary link (not password).
	 *
	 * Only users created through the module's email flow are passwordless. Existing
	 * accounts (e.g. administrators) keep normal password login even while a temp
	 * link is active, so the site owner is never locked out of wp-login.
	 *
	 * @param int $user_id User ID.
	 * @return bool
	 */
	private function mustUseTemporaryLink( int $user_id ): bool {
		return get_user_meta( $user_id, self::USER_META_PASSWORDLESS_ACCOUNT, true ) === '1';
	}

	/**
	 * Add Admin Bar Indicator
	 *
	 * Adds a warning indicator in the admin bar for temporary logins.
	 *
	 * @since 1.0.0
	 * @param \WP_Admin_Bar $wp_admin_bar Admin bar object.
	 * @return void
	 */
	public function addAdminBarIndicator( \WP_Admin_Bar $wp_admin_bar ): void {
		if ( ! is_user_logged_in() ) {
			return;
		}

		$user_id = get_current_user_id();
		if ( ! $this->hasTempSessionMeta( $user_id ) ) {
			return;
		}

		$login = $this->getActiveSessionLogin( $user_id );

		if ( ! $login ) {
			return;
		}

		$expires_ts = self::expiresAtToTimestamp( (string) $login->expires_at );
		$time_left  = $expires_ts - current_time( 'timestamp' );
		$hours_left = round( $time_left / HOUR_IN_SECONDS, 1 );

		$wp_admin_bar->add_node(
			[
				'id'    => 'tl-temporary-access',
				'title' => sprintf(
					'⚠ %s',
					sprintf(
						/* translators: %s: hours remaining */
						__( 'Temporary Access (%.1f hours left)', 'wp-powersuite' ),
						$hours_left
					)
				),
				'href'  => admin_url(),
				'meta'  => [
					'class' => 'tl-temporary-access-warning',
				],
			]
		);
	}

	/**
	 * Add Admin Bar Styles
	 *
	 * Adds CSS for the admin bar indicator.
	 *
	 * @since 1.0.0
	 * @return void
	 */
	public function addAdminBarStyles(): void {
		if ( ! is_user_logged_in() ) {
			return;
		}

		$user_id = get_current_user_id();
		if ( ! $this->hasTempSessionMeta( $user_id ) ) {
			return;
		}

		$login = $this->getActiveSessionLogin( $user_id );

		if ( ! $login ) {
			return;
		}

		?>
		<style type="text/css">
			#wpadminbar #wp-admin-bar-tl-temporary-access {
				background-color: #d63638 !important;
			}
			#wpadminbar #wp-admin-bar-tl-temporary-access .ab-item {
				color: #fff !important;
				font-weight: 600;
			}
			#wpadminbar #wp-admin-bar-tl-temporary-access:hover .ab-item {
				background-color: #b32d2e !important;
			}
		</style>
		<?php
	}

	/**
	 * Generate a one-time plain token (only shown to admins at creation / re-issue).
	 *
	 * @return string 64-character hex string.
	 */
	private function generatePlainToken(): string {
		return bin2hex( random_bytes( 32 ) );
	}

	/**
	 * Hash a plain token for database storage.
	 *
	 * @param string $plain_token Plain token from the login URL.
	 * @return string
	 */
	private function hashToken( string $plain_token ): string {
		return hash_hmac( 'sha256', $plain_token, $this->getSecretKey() );
	}

	/**
	 * Get Secret Key
	 *
	 * Gets or generates a secret key for HMAC signing.
	 *
	 * @since 1.0.0
	 * @return string Secret key.
	 */
	private function getSecretKey(): string {
		$key = get_option( 'tl_secret_key' );
		if ( empty( $key ) ) {
			$key = wp_generate_password( 64, true, true );
			update_option( 'tl_secret_key', $key, false );
		}
		return $key;
	}

	/**
	 * Create Temporary Login
	 *
	 * Creates a new temporary login record.
	 *
	 * @since 1.0.0
	 * @param array $args Login arguments.
	 * @return array{id:int,token:string}|\WP_Error Login ID and plain token, or error.
	 */
	public function createLogin( array $args ): array|\WP_Error {
		global $wpdb;

		$this->ensureDatabaseTables();

		if ( ! $this->tablesExist() ) {
			return new \WP_Error(
				'db_missing',
				__( 'Temporary Login database tables are not available.', 'wp-powersuite' )
			);
		}

		// If user_id is provided, use it (for selecting existing user)
		if ( ! empty( $args['user_id'] ) ) {
			$user_id = absint( $args['user_id'] );
			$user = get_userdata( $user_id );
			if ( ! $user ) {
				return new \WP_Error( 'invalid_user', __( 'User not found.', 'wp-powersuite' ) );
			}
			if ( in_array( 'administrator', $user->roles, true ) ) {
				$creator = wp_get_current_user();
				if ( ! $creator || ! in_array( 'administrator', $creator->roles, true ) ) {
					return new \WP_Error(
						'admin_target',
						__( 'Temporary login links for administrator accounts can only be created by administrators.', 'wp-powersuite' )
					);
				}
			}
		} elseif ( ! empty( $args['email'] ) ) {
			if ( ! is_email( $args['email'] ) ) {
				return new \WP_Error( 'invalid_email', __( 'Invalid email address.', 'wp-powersuite' ) );
			}

			$user = get_user_by( 'email', $args['email'] );
			if ( ! $user ) {
				$username = $this->generateUsername( $args['email'] );
				$row_role = sanitize_text_field( $args['role'] ?? 'subscriber' );
				if ( ! get_role( $row_role ) ) {
					$row_role = 'subscriber';
				}
				if ( $row_role === 'administrator' ) {
					$creator = wp_get_current_user();
					if ( ! $creator || ! in_array( 'administrator', $creator->roles, true ) ) {
						return new \WP_Error(
							'role_denied',
							__( 'Only administrators may create administrator accounts.', 'wp-powersuite' )
						);
					}
				}
				$user_id = wp_insert_user( [
					'user_login' => $username,
					'user_pass'  => wp_generate_password( 32, true, true ),
					'user_email' => $args['email'],
					'role'       => 'subscriber',
				] );
				if ( is_wp_error( $user_id ) ) {
					return $user_id;
				}
				update_user_meta( $user_id, self::USER_META_PASSWORDLESS_ACCOUNT, '1' );
			} else {
				$user_id = $user->ID;
				if ( in_array( 'administrator', $user->roles, true ) ) {
					$creator = wp_get_current_user();
					if ( ! $creator || ! in_array( 'administrator', $creator->roles, true ) ) {
						return new \WP_Error(
							'admin_target',
							__( 'Temporary login links for administrator accounts can only be created by administrators.', 'wp-powersuite' )
						);
					}
				}
			}
		} else {
			return new \WP_Error( 'missing_user', __( 'User ID or email is required.', 'wp-powersuite' ) );
		}

		$user = get_userdata( $user_id );
		if ( ! $user ) {
			return new \WP_Error( 'invalid_user', __( 'User not found.', 'wp-powersuite' ) );
		}

		if ( is_multisite() && is_super_admin( $user_id ) ) {
			return new \WP_Error(
				'super_admin_target',
				__( 'Temporary login links cannot be created for super admins.', 'wp-powersuite' )
			);
		}

		$row_role = sanitize_text_field( $args['role'] ?? 'subscriber' );
		if ( ! get_role( $row_role ) ) {
			$row_role = 'subscriber';
		}
		if ( $row_role === 'administrator' ) {
			$creator = wp_get_current_user();
			if ( ! $creator || ! in_array( 'administrator', $creator->roles, true ) ) {
				return new \WP_Error(
					'role_denied',
					__( 'Only administrators may assign the administrator role.', 'wp-powersuite' )
				);
			}
		}
		// Role is stored on the login row and applied for the session via user_has_cap — never set_role() here.

		$args = FeatureGate::applyFreeTierCreateArgs( $args );

		$plain_token  = $this->generatePlainToken();
		$stored_token = $this->hashToken( $plain_token );

		// Calculate expiry
		$expires_at = $this->calculateExpiry( $args['expiry_type'] ?? 'day', $args['expiry_date'] ?? null );

		$data = [
			'token'                => $stored_token,
			'user_id'              => $user_id,
			'created_by'           => get_current_user_id(),
			'created_at'           => current_time( 'mysql' ),
			'expires_at'           => $expires_at,
			'single_use'           => ! empty( $args['single_use'] ) ? 1 : 0,
			'max_uses'             => isset( $args['max_uses'] ) ? absint( $args['max_uses'] ) : 0,
			'role'                 => $row_role,
			'allowed_capabilities' => $this->encodeLoginPermissionsFromArgs( $args ),
			'ip_restriction'       => ! empty( $args['ip_restriction'] ) ? sanitize_text_field( $args['ip_restriction'] ) : null,
			'bind_user_agent'      => ! empty( $args['bind_user_agent'] ) ? 1 : 0,
			'user_agent_hash'      => null,
			'redirect_to'           => ! empty( $args['redirect_to'] ) ? esc_url_raw( $args['redirect_to'] ) : null,
			'session_version'      => 0,
		];

		$table_name = $wpdb->prefix . self::DB_TABLE_NAME;
		$result = $wpdb->insert(
			$table_name,
			$data,
			[
				'%s', // token
				'%d', // user_id
				'%d', // created_by
				'%s', // created_at
				'%s', // expires_at
				'%d', // single_use
				'%d', // max_uses
				'%s', // role
				'%s', // allowed_capabilities
				'%s', // ip_restriction
				'%d', // bind_user_agent
				'%s', // user_agent_hash
				'%s', // redirect_to
				'%d', // session_version
			]
		);

		if ( $result === false ) {
			$detail = $wpdb->last_error ? ' ' . $wpdb->last_error : '';
			return new \WP_Error(
				'db_error',
				__( 'Failed to create temporary login.', 'wp-powersuite' ) . ( defined( 'WP_DEBUG' ) && WP_DEBUG ? $detail : '' )
			);
		}

		$login_id = $wpdb->insert_id;

		// Log creation
		$this->logActivity( $login_id, $user_id, 'login_created', $this->getClientIp(), $this->getUserAgent() );

		$created_login = $this->getLoginById( $login_id );
		if ( $created_login ) {
			TemporaryLoginEmail::queue(
				TemporaryLoginEmail::EVENT_CREATED,
				$created_login,
				[
					'actor_user_id' => get_current_user_id(),
					'client_ip'     => $this->getClientIp(),
					'client_ua'     => $this->getUserAgent(),
				]
			);
		}

		return [
			'id'    => $login_id,
			'token' => $plain_token,
		];
	}

	/**
	 * Replace the stored token hash and return the new plain token (invalidates the old URL).
	 *
	 * @param int $login_id Login row ID.
	 * @return string|\WP_Error Plain token or error.
	 */
	public function regenerateLoginToken( int $login_id ): string|\WP_Error {
		$login = $this->getLoginById( $login_id );
		if ( ! $login ) {
			return new \WP_Error( 'login_not_found', __( 'Login not found.', 'wp-powersuite' ) );
		}

		if ( ! empty( $login->is_revoked ) ) {
			return new \WP_Error( 'login_revoked', __( 'Cannot refresh a revoked login.', 'wp-powersuite' ) );
		}

		if ( $this->isExpired( $login ) ) {
			return new \WP_Error( 'login_expired', __( 'Cannot refresh an expired login.', 'wp-powersuite' ) );
		}

		$plain_token = $this->generatePlainToken();

		global $wpdb;
		$table_name = $wpdb->prefix . self::DB_TABLE_NAME;
		$updated    = $wpdb->query(
			$wpdb->prepare(
				"UPDATE $table_name SET token = %s, session_version = session_version + 1 WHERE id = %d",
				$this->hashToken( $plain_token ),
				$login_id
			)
		);

		if ( $updated === false ) {
			return new \WP_Error( 'db_error', __( 'Failed to update login token.', 'wp-powersuite' ) );
		}

		$this->logActivity( $login_id, (int) $login->user_id, 'token_regenerated', $this->getClientIp(), $this->getUserAgent() );

		TemporaryLoginEmail::queue(
			TemporaryLoginEmail::EVENT_UPDATED,
			$login,
			[
				'actor_user_id' => get_current_user_id(),
				'client_ip'     => $this->getClientIp(),
				'client_ua'     => $this->getUserAgent(),
				'changes'       => [
					[
						'label' => __( 'Login URL', 'wp-powersuite' ),
						'value' => __( 'Regenerated (previous link invalidated)', 'wp-powersuite' ),
					],
				],
			]
		);

		return $plain_token;
	}

	/**
	 * Get Login By Token
	 *
	 * Retrieves a login record by token.
	 *
	 * @since 1.0.0
	 * @param string $token Token.
	 * @return object|null Login object or null.
	 */
	private function getLoginByToken( string $token ): ?object {
		if ( $token === '' || strlen( $token ) > 128 ) {
			return null;
		}

		$this->ensureDatabaseTables();
		global $wpdb;
		$table_name = $wpdb->prefix . self::DB_TABLE_NAME;

		$login = $wpdb->get_row(
			$wpdb->prepare(
				"SELECT * FROM $table_name WHERE token = %s",
				$this->hashToken( $token )
			)
		);

		if ( $login ) {
			return $login;
		}

		// Legacy rows stored the URL token verbatim (pre-1.1.0) — migrate on successful match.
		$login = $wpdb->get_row(
			$wpdb->prepare(
				"SELECT * FROM $table_name WHERE token = %s",
				$token
			)
		);

		if ( $login ) {
			$hashed = $this->hashToken( $token );
			$wpdb->update(
				$table_name,
				[ 'token' => $hashed ],
				[ 'id' => (int) $login->id ],
				[ '%s' ],
				[ '%d' ]
			);
			$login->token = $hashed;
		}

		return $login ?: null;
	}

	/**
	 * Get the active temporary-login session for the current user (avoids a table scan on most requests).
	 *
	 * @since 1.0.0
	 * @param int $user_id User ID.
	 * @return object|null Login object or null.
	 */
	/**
	 * Whether the current browser has an active temporary-login session.
	 *
	 * @param int $user_id Logged-in user ID.
	 * @return bool
	 */
	public function isCurrentBrowserTempSession( int $user_id = 0 ): bool {
		if ( $user_id <= 0 ) {
			$user_id = get_current_user_id();
		}
		if ( $user_id <= 0 ) {
			return false;
		}
		return $this->getSessionLoginIdFromCookie( $user_id ) > 0;
	}

	/**
	 * Remove legacy user-meta markers left by older versions (global per account).
	 *
	 * @return void
	 */
	public function cleanupLegacyGlobalSessionMeta(): void {
		if ( ! is_user_logged_in() ) {
			return;
		}

		$user_id = get_current_user_id();
		if ( ! absint( get_user_meta( $user_id, self::USER_META_SESSION_LOGIN, true ) ) ) {
			return;
		}

		if ( $this->getSessionLoginIdFromCookie( $user_id ) > 0 ) {
			return;
		}

		delete_user_meta( $user_id, self::USER_META_SESSION_LOGIN );
	}

	private function hasTempSessionMeta( int $user_id ): bool {
		return $this->isCurrentBrowserTempSession( $user_id );
	}

	/**
	 * Bind this browser to a temporary-login row (signed cookie + in-request cache).
	 *
	 * @param object $login Active login row.
	 * @return void
	 */
	private function establishTemporarySession( object $login ): void {
		$this->setSessionCookie( $login );
		delete_user_meta( (int) $login->user_id, self::USER_META_SESSION_LOGIN );
		$this->session_login_cache     = $login;
		$this->session_role_caps_cache = null;
		$this->registerSessionEnforcementHooks();
	}

	private function getActiveSessionLogin( int $user_id ): ?object {
		if ( $this->session_login_cache !== null ) {
			return $this->session_login_cache;
		}

		$lid = $this->getSessionLoginIdFromCookie( $user_id );
		if ( $lid > 0 ) {
			$login = $this->getLoginById( $lid );
			if (
				$login
				&& (int) $login->user_id === $user_id
				&& ! $login->is_revoked
				&& ! $this->isExpired( $login )
				&& $this->sessionCookieMatchesLogin( $login )
			) {
				$this->session_login_cache = $login;
				return $login;
			}
			$this->clearSessionCookie();
			return null;
		}
		return null;
	}

	/**
	 * @param object $login Active login row.
	 */
	private function sessionCookieMatchesLogin( object $login ): bool {
		if ( empty( $_COOKIE[ self::SESSION_COOKIE_NAME ] ) ) {
			return false;
		}

		$parsed = $this->parseSessionCookie( sanitize_text_field( wp_unslash( $_COOKIE[ self::SESSION_COOKIE_NAME ] ) ) );
		if ( ! $parsed ) {
			return false;
		}

		return (int) $parsed['login_id'] === (int) $login->id
			&& (int) $parsed['session_version'] === (int) ( $login->session_version ?? 0 );
	}

	/**
	 * @param int $user_id Expected logged-in user ID.
	 * @return int Login row ID from cookie, or 0.
	 */
	private function getSessionLoginIdFromCookie( int $user_id = 0 ): int {
		if ( $user_id <= 0 ) {
			$user_id = get_current_user_id();
		}
		if ( $user_id <= 0 || empty( $_COOKIE[ self::SESSION_COOKIE_NAME ] ) ) {
			return 0;
		}

		$parsed = $this->parseSessionCookie( sanitize_text_field( wp_unslash( $_COOKIE[ self::SESSION_COOKIE_NAME ] ) ) );
		if ( ! $parsed || (int) $parsed['user_id'] !== $user_id ) {
			return 0;
		}

		return (int) $parsed['login_id'];
	}

	/**
	 * @return string Cookie value.
	 */
	private function buildSessionCookieValue( int $login_id, int $user_id, int $session_version ): string {
		$payload = $login_id . '|' . $user_id . '|' . $session_version;
		$sig     = hash_hmac( 'sha256', $payload, $this->getSecretKey() );

		return $login_id . '.' . $user_id . '.' . $session_version . '.' . $sig;
	}

	/**
	 * @return array{login_id:int,user_id:int,session_version:int}|null
	 */
	private function parseSessionCookie( string $cookie ): ?array {
		$parts = explode( '.', $cookie, 4 );
		if ( count( $parts ) === 4 ) {
			$login_id         = absint( $parts[0] );
			$user_id          = absint( $parts[1] );
			$session_version  = absint( $parts[2] );
			$sig              = $parts[3];

			if ( ! $login_id || ! $user_id || $sig === '' ) {
				return null;
			}

			$expected = hash_hmac( 'sha256', $login_id . '|' . $user_id . '|' . $session_version, $this->getSecretKey() );
			if ( ! hash_equals( $expected, $sig ) ) {
				return null;
			}

			return [
				'login_id'        => $login_id,
				'user_id'         => $user_id,
				'session_version' => $session_version,
			];
		}

		// Legacy cookie format: login_id.user_id.sig (session_version 0).
		$legacy = explode( '.', $cookie, 3 );
		if ( count( $legacy ) !== 3 ) {
			return null;
		}

		$login_id = absint( $legacy[0] );
		$user_id  = absint( $legacy[1] );
		$sig      = $legacy[2];

		if ( ! $login_id || ! $user_id || $sig === '' ) {
			return null;
		}

		$expected = hash_hmac( 'sha256', $login_id . '|' . $user_id, $this->getSecretKey() );
		if ( ! hash_equals( $expected, $sig ) ) {
			return null;
		}

		return [
			'login_id'        => $login_id,
			'user_id'         => $user_id,
			'session_version' => 0,
		];
	}

	/**
	 * @param object $login Active login row.
	 * @return void
	 */
	private function setSessionCookie( object $login ): void {
		$expires_ts = self::expiresAtToTimestamp( (string) $login->expires_at );
		if ( $expires_ts <= current_time( 'timestamp' ) ) {
			$expires_ts = current_time( 'timestamp' ) + HOUR_IN_SECONDS;
		}

		$value = $this->buildSessionCookieValue(
			(int) $login->id,
			(int) $login->user_id,
			(int) ( $login->session_version ?? 0 )
		);

		setcookie(
			self::SESSION_COOKIE_NAME,
			$value,
			$expires_ts,
			COOKIEPATH,
			COOKIE_DOMAIN,
			is_ssl(),
			true
		);

		$_COOKIE[ self::SESSION_COOKIE_NAME ] = $value;
	}

	/**
	 * @return void
	 */
	private function clearSessionCookie(): void {
		setcookie(
			self::SESSION_COOKIE_NAME,
			'',
			time() - YEAR_IN_SECONDS,
			COOKIEPATH,
			COOKIE_DOMAIN,
			is_ssl(),
			true
		);

		unset( $_COOKIE[ self::SESSION_COOKIE_NAME ] );
	}

	/**
	 * @param int $user_id User ID.
	 * @return void
	 */
	private function clearTemporarySession( int $user_id ): void {
		$this->clearSessionCookie();
		delete_user_meta( $user_id, self::USER_META_SESSION_LOGIN );
	}

	/**
	 * Clear session marker so the next request skips temporary-login enforcement.
	 *
	 * @since 1.0.0
	 * @param mixed $user_id Passed by WordPress wp_logout when supported.
	 * @return void
	 */
	public function onWpLogoutClearSessionMeta( $user_id = 0 ): void {
		$uid = absint( $user_id );
		if ( $uid ) {
			$this->clearTemporarySession( $uid );
		} else {
			$this->clearSessionCookie();
		}
	}

	private function allowTokenAttemptFromIp(): bool {
		$attempts = (int) get_transient( self::TOKEN_RATE_TRANSIENT_PREFIX . md5( $this->getRemoteAddrStrict() ) );
		return $attempts < 5;
	}

	private function bumpTokenFailure(): void {
		$key      = self::TOKEN_RATE_TRANSIENT_PREFIX . md5( $this->getRemoteAddrStrict() );
		$attempts = (int) get_transient( $key );
		set_transient( $key, $attempts + 1, 15 * MINUTE_IN_SECONDS );
	}

	private function clearTokenRateLimitForIp(): void {
		delete_transient( self::TOKEN_RATE_TRANSIENT_PREFIX . md5( $this->getRemoteAddrStrict() ) );
	}

	/**
	 * Remote address without trusting proxy headers (used for brute-force throttling).
	 */
	private function getRemoteAddrStrict(): string {
		$ip = isset( $_SERVER['REMOTE_ADDR'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) ) : '';
		return filter_var( $ip, FILTER_VALIDATE_IP ) ? $ip : '0.0.0.0';
	}

	/**
	 * Optional admin email when a temporary link completes sign-in (disable via filter wpps_tl_notify_admin_on_login).
	 */
	private function maybeNotifyAdminLoginUsed( object $login, \WP_User $user ): void {
		TemporaryLoginEmail::queue(
			TemporaryLoginEmail::EVENT_USED,
			$login,
			[
				'actor_user_id' => (int) $user->ID,
				'client_ip'     => $this->getClientIp(),
				'client_ua'     => $this->getUserAgent(),
			]
		);
	}

	/**
	 * Check if Login is Expired
	 *
	 * @since 1.0.0
	 * @param object $login Login object.
	 * @return bool True if expired.
	 */
	/**
	 * Convert a site-local MySQL datetime (as stored in expires_at) to a Unix timestamp.
	 *
	 * @param string $expires_at MySQL datetime in site timezone.
	 * @return int
	 */
	public static function expiresAtToTimestamp( string $expires_at ): int {
		if ( trim( $expires_at ) === '' ) {
			return 0;
		}
		return (int) mysql2date( 'U', $expires_at, false );
	}

	/**
	 * Whether a login row's expires_at is in the past (site timezone).
	 *
	 * @param string $expires_at MySQL datetime from tl_temporary_logins.expires_at.
	 * @return bool
	 */
	public static function isLoginExpired( string $expires_at ): bool {
		if ( trim( $expires_at ) === '' ) {
			return false;
		}
		return self::expiresAtToTimestamp( $expires_at ) < current_time( 'timestamp' );
	}

	/**
	 * @param object $login Login row.
	 * @return bool
	 */
	private function isExpired( object $login ): bool {
		return self::isLoginExpired( (string) $login->expires_at );
	}

	/**
	 * End a broken or expired temporary session (logout + redirect).
	 *
	 * @param bool $had_temp_session Whether the user had temp session meta before validation.
	 * @return void
	 */
	private function forceEndTemporarySession( bool $had_temp_session ): void {
		if ( ! $had_temp_session || ! is_user_logged_in() ) {
			return;
		}

		$user_id = get_current_user_id();
		$this->clearTemporarySession( $user_id );
		wp_logout();
		wp_safe_redirect( wp_login_url() );
		exit;
	}

	/**
	 * Check IP Restriction
	 *
	 * @since 1.0.0
	 * @param string $restriction IP restriction (single IP or CIDR range).
	 * @return bool True if IP is allowed.
	 */
	/**
	 * IP used for login restrictions (filterable; defaults to REMOTE_ADDR).
	 *
	 * @return string
	 */
	private function getIpForRestrictionCheck(): string {
		$ip = $this->getRemoteAddrStrict();
		return (string) apply_filters( 'wpps_tl_restriction_client_ip', $ip );
	}

	/**
	 * @param string $restriction IP or CIDR.
	 * @param string $client_ip   Client IP to test.
	 * @return bool
	 */
	private function checkIpRestriction( string $restriction, string $client_ip ): bool {

		if ( strpos( $restriction, '/' ) !== false ) {
			return $this->ipInRange( $client_ip, $restriction );
		}

		// Exact match
		return $client_ip === $restriction;
	}

	/**
	 * Check if IP is in CIDR Range
	 *
	 * @since 1.0.0
	 * @param string $ip IP address.
	 * @param string $range CIDR range.
	 * @return bool True if IP is in range.
	 */
	private function ipInRange( string $ip, string $range ): bool {
		if ( strpos( $range, '/' ) === false ) {
			return $ip === $range;
		}

		list( $subnet, $mask ) = explode( '/', $range, 2 );
		$mask = (int) $mask;

		if ( filter_var( $ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 ) && filter_var( $subnet, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 ) ) {
			if ( $mask < 0 || $mask > 32 ) {
				return false;
			}
			$ip_long     = ip2long( $ip );
			$subnet_long = ip2long( $subnet );
			if ( $ip_long === false || $subnet_long === false ) {
				return false;
			}
			$mask_long = -1 << ( 32 - $mask );
			return ( $ip_long & $mask_long ) === ( $subnet_long & $mask_long );
		}

		if ( filter_var( $ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6 ) && filter_var( $subnet, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6 ) ) {
			if ( $mask < 0 || $mask > 128 ) {
				return false;
			}
			$ip_bin     = inet_pton( $ip );
			$subnet_bin = inet_pton( $subnet );
			if ( $ip_bin === false || $subnet_bin === false ) {
				return false;
			}
			$bytes = (int) floor( $mask / 8 );
			$bits  = $mask % 8;
			if ( $bytes > 0 && substr( $ip_bin, 0, $bytes ) !== substr( $subnet_bin, 0, $bytes ) ) {
				return false;
			}
			if ( $bits === 0 ) {
				return true;
			}
			$ip_byte     = ord( $ip_bin[ $bytes ] );
			$subnet_byte = ord( $subnet_bin[ $bytes ] );
			$mask_byte   = ( 0xFF << ( 8 - $bits ) ) & 0xFF;
			return ( $ip_byte & $mask_byte ) === ( $subnet_byte & $mask_byte );
		}

		return false;
	}

	/**
	 * Get Client IP
	 *
	 * @since 1.0.0
	 * @return string IP address.
	 */
	private function getClientIp(): string {
		$ip_keys = [ 'HTTP_CF_CONNECTING_IP', 'HTTP_X_REAL_IP', 'HTTP_X_FORWARDED_FOR', 'REMOTE_ADDR' ];
		foreach ( $ip_keys as $key ) {
			if ( ! empty( $_SERVER[ $key ] ) ) {
				$ip = sanitize_text_field( wp_unslash( $_SERVER[ $key ] ) );
				if ( strpos( $ip, ',' ) !== false ) {
					$ip = trim( explode( ',', $ip )[0] );
				}
				if ( filter_var( $ip, FILTER_VALIDATE_IP ) ) {
					return $ip;
				}
			}
		}
		return '0.0.0.0';
	}

	/**
	 * Get User Agent
	 *
	 * @since 1.0.0
	 * @return string User agent.
	 */
	private function getUserAgent(): string {
		return sanitize_text_field( wp_unslash( $_SERVER['HTTP_USER_AGENT'] ?? '' ) );
	}

	/**
	 * Get Current Page
	 *
	 * @since 1.0.0
	 * @return string Current page URL.
	 */
	private function getCurrentPage(): string {
		$host = isset( $_SERVER['HTTP_HOST'] ) ? sanitize_text_field( wp_unslash( $_SERVER['HTTP_HOST'] ) ) : '';
		$uri  = isset( $_SERVER['REQUEST_URI'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REQUEST_URI'] ) ) : '';
		if ( $host === '' ) {
			return $uri;
		}
		$protocol = is_ssl() ? 'https://' : 'http://';
		return $protocol . $host . $uri;
	}

	/**
	 * Calculate Expiry
	 *
	 * Calculates expiry datetime based on type and optional date.
	 *
	 * @since 1.0.0
	 * @param string      $type Expiry type.
	 * @param string|null $date Optional custom date.
	 * @return string MySQL datetime.
	 */
	private function calculateExpiry( string $type, ?string $date = null ): string {
		if ( $type === 'custom' && ! empty( $date ) ) {
			$timestamp = strtotime( $date );
			return $timestamp ? wp_date( 'Y-m-d H:i:s', $timestamp ) : current_time( 'mysql' );
		}

		$durations = [
			'hour'      => HOUR_IN_SECONDS,
			'3_hours'   => HOUR_IN_SECONDS * 3,
			'day'       => DAY_IN_SECONDS,
			'3_days'    => DAY_IN_SECONDS * 3,
			'week'      => WEEK_IN_SECONDS,
			'month'     => MONTH_IN_SECONDS,
		];

		$seconds = $durations[ $type ] ?? DAY_IN_SECONDS;
		return wp_date( 'Y-m-d H:i:s', current_time( 'timestamp' ) + $seconds );
	}

	/**
	 * Generate Username
	 *
	 * Generates a unique username from email or a random string.
	 *
	 * @since 1.0.0
	 * @param string $email_or_base Email address or base string.
	 * @return string Username.
	 */
	private function generateUsername( string $email_or_base ): string {
		// If it looks like an email, extract the base
		if ( strpos( $email_or_base, '@' ) !== false ) {
			$base = sanitize_user( explode( '@', $email_or_base )[0], true );
		} else {
			$base = sanitize_user( $email_or_base, true );
		}
		
		// If base is empty, use a random string
		if ( empty( $base ) ) {
			$base = 'temp';
		}
		
		$username = 'tl-' . $base . '-' . wp_generate_password( 8, false );
		$counter = 1;
		while ( username_exists( $username ) ) {
			$username = 'tl-' . $base . '-' . wp_generate_password( 8, false );
			$counter++;
			if ( $counter > 100 ) {
				$username = 'tl-' . wp_generate_password( 16, false );
				break;
			}
		}
		return $username;
	}

	/**
	 * Increment Login Use Count
	 *
	 * @since 1.0.0
	 * @param int $login_id Login ID.
	 * @return void
	 */
	private function incrementLoginUseCount( int $login_id ): void {
		global $wpdb;
		$table_name = $wpdb->prefix . self::DB_TABLE_NAME;
		$wpdb->query(
			$wpdb->prepare(
				"UPDATE $table_name SET used_count = used_count + 1 WHERE id = %d",
				$login_id
			)
		);
	}

	/**
	 * Update Login User Agent
	 *
	 * @since 1.0.0
	 * @param int    $login_id Login ID.
	 * @param string $user_agent_hash User agent hash.
	 * @return void
	 */
	private function updateLoginUserAgent( int $login_id, string $user_agent_hash ): void {
		global $wpdb;
		$table_name = $wpdb->prefix . self::DB_TABLE_NAME;
		$wpdb->update(
			$table_name,
			[ 'user_agent_hash' => $user_agent_hash ],
			[ 'id' => $login_id ],
			[ '%s' ],
			[ '%d' ]
		);
	}


	/**
	 * Redirect After Login
	 *
	 * @since 1.0.0
	 * @param object $login Login object.
	 * @return void
	 */
	private function redirectAfterLogin( object $login ): void {
		$user      = get_userdata( (int) $login->user_id );
		$role_slug = sanitize_text_field( $login->role ?? 'subscriber' );

		if ( ! empty( $login->redirect_to ) ) {
			$redirect_to = remove_query_arg( self::TOKEN_PARAM, $login->redirect_to );
		} elseif ( $this->roleCanAccessDashboard( $role_slug ) ) {
			$redirect_to = admin_url();
		} else {
			$redirect_to = home_url( '/' );
		}

		$requested_redirect_to = '';
		if ( ! empty( $_GET['redirect_to'] ) ) {
			$requested_redirect_to = esc_url_raw( wp_unslash( $_GET['redirect_to'] ) );
		}

		if ( $user instanceof \WP_User ) {
			if ( empty( $login->redirect_to ) && $this->roleCanAccessDashboard( $role_slug ) ) {
				// WooCommerce and similar plugins redirect subscribers to my-account; keep editors/admins in wp-admin.
				add_filter( 'login_redirect', static fn() => admin_url(), 9999 );
				add_filter( 'woocommerce_login_redirect', static fn() => admin_url(), 9999 );
			} else {
				$this->registerRedirectAfterLoginHooks();
				/**
				 * Same filter chain as wp-login (Redirect After Login module hooks here).
				 *
				 * @param string   $redirect_to           Default redirect URL.
				 * @param string   $requested_redirect_to redirect_to query arg from the magic link, if any.
				 * @param \WP_User $user                  Authenticated user.
				 */
				$redirect_to = apply_filters( 'login_redirect', $redirect_to, $requested_redirect_to, $user );
				if ( class_exists( 'WooCommerce' ) ) {
					$redirect_to = apply_filters( 'woocommerce_login_redirect', (string) $redirect_to, $user );
				}
			}
		}

		wp_safe_redirect( wp_validate_redirect( $redirect_to, admin_url() ) );
		exit;
	}

	/**
	 * Whether a temporary session role should land in wp-admin after login.
	 *
	 * @param string $role_slug WordPress role slug stored on the login row.
	 */
	private function roleCanAccessDashboard( string $role_slug ): bool {
		$role = get_role( $role_slug );
		if ( ! $role ) {
			return false;
		}

		$caps = $role->capabilities;

		return ! empty( $caps['manage_options'] ) || ! empty( $caps['edit_posts'] );
	}

	/**
	 * Register Redirect After Login filters for token-based sign-in (no wp-login.php).
	 *
	 * @return void
	 */
	private function registerRedirectAfterLoginHooks(): void {
		if ( ! class_exists( 'WP_PowerSuite\\Core\\ModuleManager' ) ) {
			return;
		}

		$module = \WP_PowerSuite\Core\ModuleManager::getInstance()->getModule( 'redirect-after-login' );
		if ( $module instanceof \RedirectAfterLogin\Module && $module->isEnabled() ) {
			$module->registerRedirectHooks();
		}
	}

	/**
	 * Log Activity
	 *
	 * Logs an activity event.
	 *
	 * @since 1.0.0
	 * @param int    $login_id Login ID.
	 * @param int    $user_id User ID.
	 * @param string $action Action type.
	 * @param string $ip_address IP address.
	 * @param string $user_agent User agent.
	 * @param string $page_accessed Optional page accessed.
	 * @return void
	 */
	private function logActivity( int $login_id, int $user_id, string $action, string $ip_address, string $user_agent, string $page_accessed = '' ): void {
		global $wpdb;
		$table_name = $wpdb->prefix . self::DB_LOG_TABLE_NAME;
		$wpdb->insert(
			$table_name,
			[
				'login_id'      => $login_id,
				'user_id'       => $user_id,
				'action'        => $action,
				'ip_address'    => $ip_address,
				'user_agent'    => $user_agent,
				'page_accessed' => $this->redactSensitiveUrlForLog( $page_accessed ),
				'logged_at'     => current_time( 'mysql' ),
			],
			[ '%d', '%d', '%s', '%s', '%s', '%s', '%s' ]
		);
	}

	/**
	 * Remove secrets from URLs before storing or displaying activity log entries.
	 *
	 * Magic-link tokens must never be persisted in tl_activity_logs — only hashed in tl_temporary_logins.
	 */
	private function redactSensitiveUrlForLog( string $url ): string {
		if ( $url === '' ) {
			return '';
		}

		$redacted = remove_query_arg( self::TOKEN_PARAM, $url );

		return rtrim( $redacted, '?' );
	}

	/**
	 * Get All Logins
	 *
	 * Gets all temporary logins with optional filters.
	 *
	 * @since 1.0.0
	 * @param array $args Query arguments.
	 * @return array Login records.
	 */
	public function getAllLogins( array $args = [] ): array {
		$this->ensureDatabaseTables();
		global $wpdb;
		$table_name = $wpdb->prefix . self::DB_TABLE_NAME;

		$where = [ '1=1' ];
		$where_values = [];

		if ( ! empty( $args['status'] ) ) {
			if ( $args['status'] === 'active' ) {
				$where[] = 'is_revoked = 0 AND expires_at > %s';
				$where_values[] = current_time( 'mysql' );
			} elseif ( $args['status'] === 'expired' ) {
				$where[] = 'expires_at <= %s';
				$where_values[] = current_time( 'mysql' );
			} elseif ( $args['status'] === 'revoked' ) {
				$where[] = 'is_revoked = 1';
			}
		}

		$where_sql = implode( ' AND ', $where );
		$sql = "SELECT * FROM $table_name WHERE $where_sql ORDER BY created_at DESC";

		if ( ! empty( $where_values ) ) {
			$sql = $wpdb->prepare( $sql, $where_values );
		}

		return $wpdb->get_results( $sql );
	}

	/**
	 * Status counts for admin list filters (single query).
	 *
	 * @return array{all:int,active:int,expired:int,revoked:int}
	 */
	public function getLoginCounts(): array {
		$this->ensureDatabaseTables();
		global $wpdb;
		$table_name = $wpdb->prefix . self::DB_TABLE_NAME;
		$now        = current_time( 'mysql' );

		$row = $wpdb->get_row(
			$wpdb->prepare(
				"SELECT
					COUNT(*) AS total,
					SUM( CASE WHEN is_revoked = 0 AND expires_at > %s THEN 1 ELSE 0 END ) AS active,
					SUM( CASE WHEN is_revoked = 0 AND expires_at <= %s THEN 1 ELSE 0 END ) AS expired,
					SUM( CASE WHEN is_revoked = 1 THEN 1 ELSE 0 END ) AS revoked
				FROM $table_name",
				$now,
				$now
			),
			ARRAY_A
		);

		return [
			'all'     => isset( $row['total'] ) ? (int) $row['total'] : 0,
			'active'  => isset( $row['active'] ) ? (int) $row['active'] : 0,
			'expired' => isset( $row['expired'] ) ? (int) $row['expired'] : 0,
			'revoked' => isset( $row['revoked'] ) ? (int) $row['revoked'] : 0,
		];
	}

	/**
	 * Revoke Login
	 *
	 * Revokes a temporary login.
	 *
	 * @since 1.0.0
	 * @param int $login_id Login ID.
	 * @return bool Success.
	 */
	public function revokeLogin( int $login_id ): bool {
		global $wpdb;
		$table_name = $wpdb->prefix . self::DB_TABLE_NAME;
		$result = $wpdb->query(
			$wpdb->prepare(
				"UPDATE $table_name SET is_revoked = 1, revoked_at = %s, revoked_by = %d WHERE id = %d",
				current_time( 'mysql' ),
				get_current_user_id(),
				$login_id
			)
		);

		if ( $result !== false ) {
			$login = $this->getLoginById( $login_id );
			if ( $login ) {
				$this->logActivity( $login_id, $login->user_id, 'login_revoked', $this->getClientIp(), $this->getUserAgent() );
				$this->terminateSessionsForLogin( $login_id );
				TemporaryLoginEmail::queue(
					TemporaryLoginEmail::EVENT_REVOKED,
					$login,
					[
						'actor_user_id' => (int) ( $login->revoked_by ?? get_current_user_id() ),
						'client_ip'     => $this->getClientIp(),
						'client_ua'     => $this->getUserAgent(),
					]
				);
			}
		}

		return $result !== false;
	}

	/**
	 * End every session tied to a login row (revoke / delete).
	 *
	 * @param int $login_id Login row ID.
	 * @return void
	 */
	private function terminateSessionsForLogin( int $login_id ): void {
		global $wpdb;
		$table_name = $wpdb->prefix . self::DB_TABLE_NAME;
		$wpdb->query(
			$wpdb->prepare(
				"UPDATE $table_name SET session_version = session_version + 1 WHERE id = %d",
				$login_id
			)
		);

		$users = get_users(
			[
				'meta_key'   => self::USER_META_SESSION_LOGIN,
				'meta_value' => (string) $login_id,
				'fields'     => 'ID',
			]
		);

		foreach ( $users as $uid ) {
			delete_user_meta( absint( $uid ), self::USER_META_SESSION_LOGIN );
		}

		if ( $this->getSessionLoginIdFromCookie() === $login_id ) {
			$this->clearTemporarySession( get_current_user_id() );
			wp_logout();
		}
	}

	/**
	 * Re-enables a revoked login and rotates the token (invalidates old URLs and sessions).
	 *
	 * @since 1.0.0
	 * @param int $login_id Login ID.
	 * @return bool Success.
	 */
	public function enableLogin( int $login_id ): bool {
		global $wpdb;
		$table_name = $wpdb->prefix . self::DB_TABLE_NAME;

		$login = $this->getLoginById( $login_id );
		if ( ! $login ) {
			return false;
		}

		if ( $this->isExpired( $login ) ) {
			return false;
		}

		$result = $wpdb->update(
			$table_name,
			[
				'is_revoked' => 0,
				'revoked_at' => null,
				'revoked_by' => null,
			],
			[ 'id' => $login_id ],
			[ '%d', '%s', '%d' ],
			[ '%d' ]
		);

		if ( $result === false ) {
			return false;
		}

		$plain = $this->regenerateLoginToken( $login_id );
		if ( is_wp_error( $plain ) ) {
			return false;
		}

		$this->logActivity( $login_id, (int) $login->user_id, 'login_enabled', $this->getClientIp(), $this->getUserAgent() );

		return true;
	}

	/**
	 * Delete Login
	 *
	 * Permanently deletes a temporary login.
	 *
	 * @since 1.0.0
	 * @param int $login_id Login ID.
	 * @return bool Success.
	 */
	public function deleteLogin( int $login_id ): bool {
		global $wpdb;
		$table_name = $wpdb->prefix . self::DB_TABLE_NAME;
		$log_table_name = $wpdb->prefix . self::DB_LOG_TABLE_NAME;

		$login = $this->getLoginById( $login_id );
		$user_id = $login ? (int) $login->user_id : 0;

		$wpdb->delete( $log_table_name, [ 'login_id' => $login_id ], [ '%d' ] );

		$this->terminateSessionsForLogin( $login_id );

		$result = $wpdb->delete( $table_name, [ 'id' => $login_id ], [ '%d' ] );

		if ( $result !== false && $user_id > 0 ) {
			$this->maybeDeleteOrphanPasswordlessUser( $user_id );
		}

		return $result !== false;
	}

	/**
	 * Update Login
	 *
	 * Updates an existing temporary login.
	 *
	 * @since 1.0.0
	 * @param int   $login_id Login ID.
	 * @param array $args Update arguments.
	 * @return bool|\WP_Error Success or error.
	 */
	public function updateLogin( int $login_id, array $args ): bool|\WP_Error {
		global $wpdb;
		$table_name = $wpdb->prefix . self::DB_TABLE_NAME;

		$login = $this->getLoginById( $login_id );
		if ( ! $login ) {
			return new \WP_Error( 'login_not_found', __( 'Login not found.', 'wp-powersuite' ) );
		}

		$args = FeatureGate::applyFreeTierUpdateArgs( $args, $login );

		$update_data = [];

		if ( isset( $args['role'] ) ) {
			$new_role = sanitize_text_field( $args['role'] );
			if ( ! get_role( $new_role ) ) {
				return new \WP_Error( 'invalid_role', __( 'Invalid role.', 'wp-powersuite' ) );
			}
			if ( $new_role === 'administrator' ) {
				$creator = wp_get_current_user();
				if ( ! $creator || ! in_array( 'administrator', $creator->roles, true ) ) {
					return new \WP_Error(
						'role_denied',
						__( 'Only administrators may assign the administrator role.', 'wp-powersuite' )
					);
				}
			}
			$update_data['role'] = $new_role;
		}

		if ( isset( $args['expiry_type'] ) || isset( $args['expiry_date'] ) ) {
			$expiry_type = $args['expiry_type'] ?? 'day';
			$expiry_date = $args['expiry_date'] ?? null;
			$update_data['expires_at'] = $this->calculateExpiry( $expiry_type, $expiry_date );
		}

		if ( isset( $args['single_use'] ) ) {
			$update_data['single_use'] = $args['single_use'] ? 1 : 0;
		}

		if ( isset( $args['max_uses'] ) ) {
			$update_data['max_uses'] = absint( $args['max_uses'] );
		}

		if ( isset( $args['ip_restriction'] ) ) {
			$update_data['ip_restriction'] = ! empty( $args['ip_restriction'] ) ? sanitize_text_field( $args['ip_restriction'] ) : null;
		}

		if ( isset( $args['redirect_to'] ) ) {
			$update_data['redirect_to'] = ! empty( $args['redirect_to'] ) ? esc_url_raw( $args['redirect_to'] ) : null;
		}

		if ( array_key_exists( 'bind_user_agent', $args ) ) {
			$update_data['bind_user_agent'] = ! empty( $args['bind_user_agent'] ) ? 1 : 0;
			if ( empty( $args['bind_user_agent'] ) ) {
				$update_data['user_agent_hash'] = null;
			}
		}

		if ( $this->argsIncludePermissionFields( $args ) ) {
			$update_data['allowed_capabilities'] = $this->encodeLoginPermissionsFromArgs( $args );
		}

		if ( empty( $update_data ) ) {
			return true; // Nothing to update
		}

		$changes = TemporaryLoginEmail::buildUpdateChanges( $login, $update_data );

		$result = $wpdb->update(
			$table_name,
			$update_data,
			[ 'id' => $login_id ],
			array_fill( 0, count( $update_data ), '%s' ),
			[ '%d' ]
		);

		if ( $result !== false ) {
			$this->logActivity( $login_id, $login->user_id, 'login_updated', $this->getClientIp(), $this->getUserAgent() );
			$updated_login = $this->getLoginById( $login_id );
			if ( $updated_login && ! empty( $changes ) ) {
				TemporaryLoginEmail::queue(
					TemporaryLoginEmail::EVENT_UPDATED,
					$updated_login,
					[
						'actor_user_id' => get_current_user_id(),
						'client_ip'     => $this->getClientIp(),
						'client_ua'     => $this->getUserAgent(),
						'changes'       => $changes,
					]
				);
			}
		}

		return $result !== false;
	}

	/**
	 * Get Login By ID
	 *
	 * @since 1.0.0
	 * @param int $login_id Login ID.
	 * @return object|null Login object.
	 */
	public function getLoginById( int $login_id ): ?object {
		$this->ensureDatabaseTables();
		global $wpdb;
		$table_name = $wpdb->prefix . self::DB_TABLE_NAME;

		return $wpdb->get_row(
			$wpdb->prepare( "SELECT * FROM $table_name WHERE id = %d", $login_id )
		) ?: null;
	}

	/**
	 * Expire Login
	 *
	 * Sets the expiry time to now so the login becomes expired immediately.
	 *
	 * @since 1.0.0
	 * @param int $login_id Login ID.
	 * @return bool Success.
	 */
	public function expireLogin( int $login_id ): bool {
		global $wpdb;
		$table_name = $wpdb->prefix . self::DB_TABLE_NAME;
		return $wpdb->update(
			$table_name,
			[ 'expires_at' => current_time( 'mysql' ) ],
			[ 'id' => $login_id ],
			[ '%s' ],
			[ '%d' ]
		) !== false;
	}

	/**
	 * Extend Expiry
	 *
	 * Extends the expiry time for a login.
	 *
	 * @since 1.0.0
	 * @param int    $login_id Login ID.
	 * @param string $new_expiry New expiry datetime.
	 * @return bool Success.
	 */
	public function extendExpiry( int $login_id, string $new_expiry ): bool {
		global $wpdb;
		$table_name = $wpdb->prefix . self::DB_TABLE_NAME;
		return $wpdb->update(
			$table_name,
			[ 'expires_at' => $new_expiry ],
			[ 'id' => $login_id ],
			[ '%s' ],
			[ '%d' ]
		) !== false;
	}

	/**
	 * Get Activity Logs
	 *
	 * Gets activity logs for a login or all logins.
	 *
	 * @since 1.0.0
	 * @param array $args Query arguments.
	 * @return array Log records.
	 */
	public function getActivityLogs( array $args = [] ): array {
		$this->ensureDatabaseTables();
		global $wpdb;
		$table_name = $wpdb->prefix . self::DB_LOG_TABLE_NAME;

		$where = [ '1=1' ];
		$where_values = [];

		if ( ! empty( $args['login_id'] ) ) {
			$where[] = 'login_id = %d';
			$where_values[] = $args['login_id'];
		}

		if ( ! empty( $args['user_id'] ) ) {
			$where[] = 'user_id = %d';
			$where_values[] = $args['user_id'];
		}

		if ( ! empty( $args['exclude_noise'] ) ) {
			$where[] = "action NOT IN ('page_access', 'login_created')";
		}

		$where_sql = implode( ' AND ', $where );
		$sql = "SELECT * FROM $table_name WHERE $where_sql ORDER BY logged_at DESC";

		if ( ! empty( $where_values ) ) {
			$sql = $wpdb->prepare( $sql, $where_values );
		}

		if ( ! empty( $args['limit'] ) ) {
			$sql .= ' LIMIT ' . absint( $args['limit'] );
		}

		$results = $wpdb->get_results( $sql );
		if ( ! $results ) {
			return [];
		}

		foreach ( $results as $log ) {
			if ( ! empty( $log->page_accessed ) ) {
				$log->page_accessed = $this->redactSensitiveUrlForLog( (string) $log->page_accessed );
			}
		}

		return $results;
	}

	/**
	 * Cleanup Expired Logins
	 *
	 * Removes expired login records (cron job).
	 *
	 * @since 1.0.0
	 * @return void
	 */
	public function cleanupExpiredLogins(): void {
		if ( ! $this->isEnabled() ) {
			return;
		}
		$this->ensureDatabaseTables();
		global $wpdb;
		$table_name = $wpdb->prefix . self::DB_TABLE_NAME;
		$now        = current_time( 'mysql' );

		$expired_user_ids = $wpdb->get_col(
			$wpdb->prepare(
				"SELECT DISTINCT user_id FROM $table_name WHERE expires_at < %s AND is_revoked = 0",
				$now
			)
		);

		$wpdb->query(
			$wpdb->prepare(
				"DELETE FROM $table_name WHERE expires_at < %s AND is_revoked = 0",
				$now
			)
		);

		if ( is_array( $expired_user_ids ) ) {
			foreach ( $expired_user_ids as $user_id ) {
				$user_id = absint( $user_id );
				if ( $user_id > 0 ) {
					$this->maybeDeleteOrphanPasswordlessUser( $user_id );
				}
			}
		}
	}

	/**
	 * Remove link-only users that no longer have any login rows.
	 */
	private function maybeDeleteOrphanPasswordlessUser( int $user_id ): void {
		if ( ! $this->mustUseTemporaryLink( $user_id ) ) {
			return;
		}

		global $wpdb;
		$table_name = $wpdb->prefix . self::DB_TABLE_NAME;
		$remaining  = (int) $wpdb->get_var(
			$wpdb->prepare(
				"SELECT COUNT(*) FROM $table_name WHERE user_id = %d",
				$user_id
			)
		);

		if ( $remaining === 0 ) {
			require_once ABSPATH . 'wp-admin/includes/user.php';
			wp_delete_user( $user_id );
		}
	}

	/**
	 * Prune activity logs older than {@see LOG_RETENTION_DAYS}.
	 */
	public function cleanupOldActivityLogs(): void {
		if ( ! $this->isEnabled() ) {
			return;
		}
		$this->ensureDatabaseTables();
		global $wpdb;
		$log_table = $wpdb->prefix . self::DB_LOG_TABLE_NAME;
		$cutoff    = wp_date( 'Y-m-d H:i:s', current_time( 'timestamp' ) - ( self::LOG_RETENTION_DAYS * DAY_IN_SECONDS ) );
		$wpdb->query(
			$wpdb->prepare(
				"DELETE FROM $log_table WHERE logged_at < %s",
				$cutoff
			)
		);
	}

	/**
	 * Verify AJAX nonce and return JSON (not bare -1) on failure.
	 */
	private function verifyAjaxNonce(): void {
		$nonce = isset( $_REQUEST['nonce'] ) ? sanitize_text_field( wp_unslash( (string) $_REQUEST['nonce'] ) ) : '';
		if ( ! wp_verify_nonce( $nonce, 'tl_nonce' ) ) {
			wp_send_json_error(
				[ 'message' => __( 'Security check failed. Refresh the page and try again.', 'wp-powersuite' ) ],
				403
			);
		}
	}

	/**
	 * AJAX: Create Login
	 *
	 * @since 1.0.0
	 * @return void
	 */
	public function ajaxCreateLogin(): void {
		$this->verifyAjaxNonce();

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( [ 'message' => __( 'Permission denied.', 'wp-powersuite' ) ] );
		}

		$user_id = isset( $_POST['user_id'] ) ? absint( $_POST['user_id'] ) : 0;
		$email = isset( $_POST['email'] ) ? sanitize_email( wp_unslash( $_POST['email'] ) ) : '';

		// Validate: need either user_id or email
		if ( empty( $user_id ) && empty( $email ) ) {
			wp_send_json_error( [ 'message' => __( 'Please select a user or enter an email address.', 'wp-powersuite' ) ] );
		}

		if ( ! empty( $email ) && ! is_email( $email ) ) {
			wp_send_json_error( [ 'message' => __( 'Invalid email address.', 'wp-powersuite' ) ] );
		}

		$args = [
			'user_id'              => $user_id,
			'email'                => $email,
			'role'                 => isset( $_POST['role'] ) ? sanitize_text_field( $_POST['role'] ) : 'subscriber',
			'expiry_type'          => isset( $_POST['expiry_type'] ) ? sanitize_text_field( $_POST['expiry_type'] ) : 'day',
			'expiry_date'          => isset( $_POST['expiry_date'] ) ? sanitize_text_field( $_POST['expiry_date'] ) : null,
			'single_use'           => isset( $_POST['single_use'] ) && $_POST['single_use'] === '1',
			'max_uses'             => isset( $_POST['max_uses'] ) ? absint( $_POST['max_uses'] ) : 0,
			'ip_restriction'       => isset( $_POST['ip_restriction'] ) ? sanitize_text_field( $_POST['ip_restriction'] ) : '',
			'bind_user_agent'      => isset( $_POST['bind_user_agent'] ) && $_POST['bind_user_agent'] === '1',
			'redirect_to'          => isset( $_POST['redirect_to'] ) ? esc_url_raw( $_POST['redirect_to'] ) : '',
			self::PERM_INSTALL_PLUGINS => isset( $_POST[ self::PERM_INSTALL_PLUGINS ] ) && $_POST[ self::PERM_INSTALL_PLUGINS ] === '1',
			self::PERM_DELETE_PLUGINS  => isset( $_POST[ self::PERM_DELETE_PLUGINS ] ) && $_POST[ self::PERM_DELETE_PLUGINS ] === '1',
			self::PERM_INSTALL_THEMES  => isset( $_POST[ self::PERM_INSTALL_THEMES ] ) && $_POST[ self::PERM_INSTALL_THEMES ] === '1',
			self::PERM_DELETE_THEMES   => isset( $_POST[ self::PERM_DELETE_THEMES ] ) && $_POST[ self::PERM_DELETE_THEMES ] === '1',
		];

		$result = $this->createLogin( $args );

		if ( is_wp_error( $result ) ) {
			wp_send_json_error( [ 'message' => $result->get_error_message() ] );
		}

		$login_url = add_query_arg( self::TOKEN_PARAM, $result['token'], home_url() );

		wp_send_json_success(
			[
				'login_id'  => $result['id'],
				'login_url' => $login_url,
				'message'   => __( 'Temporary login created successfully.', 'wp-powersuite' ),
			]
		);
	}

	/**
	 * AJAX: Issue a fresh copy link (rotates token; previous URL stops working).
	 *
	 * @return void
	 */
	public function ajaxIssueCopyLink(): void {
		$this->verifyAjaxNonce();

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( [ 'message' => __( 'Permission denied.', 'wp-powersuite' ) ] );
		}

		$login_id = isset( $_POST['login_id'] ) ? absint( $_POST['login_id'] ) : 0;
		if ( ! $login_id ) {
			wp_send_json_error( [ 'message' => __( 'Invalid login ID.', 'wp-powersuite' ) ] );
		}

		$plain = $this->regenerateLoginToken( $login_id );
		if ( is_wp_error( $plain ) ) {
			wp_send_json_error( [ 'message' => $plain->get_error_message() ] );
		}

		wp_send_json_success(
			[
				'login_url' => add_query_arg( self::TOKEN_PARAM, $plain, home_url() ),
			]
		);
	}

	/**
	 * AJAX: Search users for the create form.
	 *
	 * @return void
	 */
	public function ajaxSearchUsers(): void {
		$this->verifyAjaxNonce();

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( [ 'message' => __( 'Permission denied.', 'wp-powersuite' ) ] );
		}

		$search = isset( $_GET['q'] ) ? sanitize_text_field( wp_unslash( $_GET['q'] ) ) : '';
		if ( strlen( $search ) < 2 ) {
			wp_send_json_success( [ 'users' => [] ] );
		}

		$query = new \WP_User_Query(
			[
				'number'         => 20,
				'search'         => '*' . $search . '*',
				'search_columns' => [ 'user_login', 'user_nicename', 'user_email', 'display_name' ],
				'orderby'        => 'display_name',
				'order'          => 'ASC',
			]
		);

		$users = [];
		foreach ( $query->get_results() as $user ) {
			if ( ! $user instanceof \WP_User ) {
				continue;
			}
			$label = $user->display_name ?: $user->user_login;
			if ( $user->user_email ) {
				$label .= ' (' . $user->user_email . ')';
			}
			$users[] = [
				'id'    => (int) $user->ID,
				'label' => $label,
			];
		}

		wp_send_json_success( [ 'users' => $users ] );
	}

	/**
	 * AJAX: Revoke Login
	 *
	 * @since 1.0.0
	 * @return void
	 */
	public function ajaxRevokeLogin(): void {
		$this->verifyAjaxNonce();

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( [ 'message' => __( 'Permission denied.', 'wp-powersuite' ) ] );
		}

		$login_id = isset( $_POST['login_id'] ) ? absint( $_POST['login_id'] ) : 0;

		if ( empty( $login_id ) ) {
			wp_send_json_error( [ 'message' => __( 'Invalid login ID.', 'wp-powersuite' ) ] );
		}

		$result = $this->revokeLogin( $login_id );

		if ( $result ) {
			wp_send_json_success( [ 'message' => __( 'Login revoked successfully.', 'wp-powersuite' ) ] );
		} else {
			wp_send_json_error( [ 'message' => __( 'Failed to revoke login.', 'wp-powersuite' ) ] );
		}
	}

	/**
	 * AJAX: Enable Login
	 *
	 * @since 1.0.0
	 * @return void
	 */
	public function ajaxEnableLogin(): void {
		$this->verifyAjaxNonce();

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( [ 'message' => __( 'Permission denied.', 'wp-powersuite' ) ] );
		}

		$login_id = isset( $_POST['login_id'] ) ? absint( $_POST['login_id'] ) : 0;

		if ( empty( $login_id ) ) {
			wp_send_json_error( [ 'message' => __( 'Invalid login ID.', 'wp-powersuite' ) ] );
		}

		$result = $this->enableLogin( $login_id );

		if ( $result ) {
			wp_send_json_success( [ 'message' => __( 'Login enabled successfully.', 'wp-powersuite' ) ] );
		} else {
			wp_send_json_error( [ 'message' => __( 'Failed to enable login.', 'wp-powersuite' ) ] );
		}
	}

	/**
	 * AJAX: Delete Login
	 *
	 * @since 1.0.0
	 * @return void
	 */
	public function ajaxDeleteLogin(): void {
		$this->verifyAjaxNonce();

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( [ 'message' => __( 'Permission denied.', 'wp-powersuite' ) ] );
		}

		$login_id = isset( $_POST['login_id'] ) ? absint( $_POST['login_id'] ) : 0;

		if ( empty( $login_id ) ) {
			wp_send_json_error( [ 'message' => __( 'Invalid login ID.', 'wp-powersuite' ) ] );
		}

		$result = $this->deleteLogin( $login_id );

		if ( $result ) {
			wp_send_json_success( [ 'message' => __( 'Login deleted successfully.', 'wp-powersuite' ) ] );
		} else {
			wp_send_json_error( [ 'message' => __( 'Failed to delete login.', 'wp-powersuite' ) ] );
		}
	}

	/**
	 * AJAX: Get Login
	 *
	 * @since 1.0.0
	 * @return void
	 */
	public function ajaxGetLogin(): void {
		$this->verifyAjaxNonce();

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( [ 'message' => __( 'Permission denied.', 'wp-powersuite' ) ] );
		}

		$login_id = isset( $_GET['login_id'] ) ? absint( $_GET['login_id'] ) : 0;

		if ( empty( $login_id ) ) {
			wp_send_json_error( [ 'message' => __( 'Invalid login ID.', 'wp-powersuite' ) ] );
		}

		$login = $this->getLoginById( $login_id );
		if ( ! $login ) {
			wp_send_json_error( [ 'message' => __( 'Login not found.', 'wp-powersuite' ) ] );
		}

		$user  = get_userdata( $login->user_id );
		$perms = $this->getLoginPermissions( $login );

		wp_send_json_success( [
			'login' => [
				'id'              => $login->id,
				'user_id'         => $login->user_id,
				'user_email'      => $user ? $user->user_email : '',
				'role'            => $login->role,
				'expiry_type'     => $this->getExpiryType( $login->expires_at ),
				'expiry_date'     => date( 'Y-m-d\TH:i', strtotime( $login->expires_at ) ),
				'single_use'      => (bool) $login->single_use,
				'max_uses'        => $login->max_uses,
				'ip_restriction'  => $login->ip_restriction,
				'bind_user_agent' => ! empty( $login->bind_user_agent ),
				'redirect_to'     => $login->redirect_to,
				'install_plugins' => $perms[ self::PERM_INSTALL_PLUGINS ],
				'delete_plugins'  => $perms[ self::PERM_DELETE_PLUGINS ],
				'install_themes'  => $perms[ self::PERM_INSTALL_THEMES ],
				'delete_themes'   => $perms[ self::PERM_DELETE_THEMES ],
			],
		] );
	}

	/**
	 * AJAX: Update Login
	 *
	 * @since 1.0.0
	 * @return void
	 */
	public function ajaxUpdateLogin(): void {
		$this->verifyAjaxNonce();

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( [ 'message' => __( 'Permission denied.', 'wp-powersuite' ) ] );
		}

		$login_id = isset( $_POST['login_id'] ) ? absint( $_POST['login_id'] ) : 0;

		if ( empty( $login_id ) ) {
			wp_send_json_error( [ 'message' => __( 'Invalid login ID.', 'wp-powersuite' ) ] );
		}

		$args = [
			'role'            => isset( $_POST['role'] ) ? sanitize_text_field( $_POST['role'] ) : null,
			'expiry_type'     => isset( $_POST['expiry_type'] ) ? sanitize_text_field( $_POST['expiry_type'] ) : null,
			'expiry_date'     => isset( $_POST['expiry_date'] ) ? sanitize_text_field( $_POST['expiry_date'] ) : null,
			'single_use'      => isset( $_POST['single_use'] ) && $_POST['single_use'] === '1',
			'max_uses'        => isset( $_POST['max_uses'] ) ? absint( $_POST['max_uses'] ) : null,
			'ip_restriction'  => isset( $_POST['ip_restriction'] ) ? sanitize_text_field( $_POST['ip_restriction'] ) : null,
			'redirect_to'     => isset( $_POST['redirect_to'] ) ? esc_url_raw( $_POST['redirect_to'] ) : null,
			'bind_user_agent' => isset( $_POST['bind_user_agent'] ) && $_POST['bind_user_agent'] === '1',
			self::PERM_INSTALL_PLUGINS => isset( $_POST[ self::PERM_INSTALL_PLUGINS ] ) && $_POST[ self::PERM_INSTALL_PLUGINS ] === '1',
			self::PERM_DELETE_PLUGINS  => isset( $_POST[ self::PERM_DELETE_PLUGINS ] ) && $_POST[ self::PERM_DELETE_PLUGINS ] === '1',
			self::PERM_INSTALL_THEMES  => isset( $_POST[ self::PERM_INSTALL_THEMES ] ) && $_POST[ self::PERM_INSTALL_THEMES ] === '1',
			self::PERM_DELETE_THEMES   => isset( $_POST[ self::PERM_DELETE_THEMES ] ) && $_POST[ self::PERM_DELETE_THEMES ] === '1',
		];

		$args = array_filter(
			$args,
			static function ( $value ) {
				return $value !== null;
			}
		);

		$result = $this->updateLogin( $login_id, $args );

		if ( is_wp_error( $result ) ) {
			wp_send_json_error( [ 'message' => $result->get_error_message() ] );
		}

		if ( $result ) {
			wp_send_json_success( [ 'message' => __( 'Login updated successfully.', 'wp-powersuite' ) ] );
		} else {
			wp_send_json_error( [ 'message' => __( 'Failed to update login.', 'wp-powersuite' ) ] );
		}
	}

	/**
	 * AJAX: Get Logs
	 *
	 * @since 1.0.0
	 * @return void
	 */
	public function ajaxGetLogs(): void {
		$this->verifyAjaxNonce();

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( [ 'message' => __( 'Permission denied.', 'wp-powersuite' ) ] );
		}

		$login_id = isset( $_GET['login_id'] ) ? absint( $_GET['login_id'] ) : 0;

		if ( empty( $login_id ) ) {
			wp_send_json_error( [ 'message' => __( 'Invalid login ID.', 'wp-powersuite' ) ] );
		}

		$logs = $this->getActivityLogs(
			[
				'login_id'       => $login_id,
				'limit'          => 100,
				'exclude_noise'  => true,
			]
		);

		wp_send_json_success( [ 'logs' => $logs ] );
	}

	/**
	 * Get Expiry Type
	 *
	 * Determines expiry type from expiry date.
	 *
	 * @since 1.0.0
	 * @param string $expires_at Expiry datetime.
	 * @return string Expiry type.
	 */
	private function getExpiryType( string $expires_at ): string {
		$diff = self::expiresAtToTimestamp( $expires_at ) - current_time( 'timestamp' );

		if ( $diff <= HOUR_IN_SECONDS ) {
			return 'hour';
		} elseif ( $diff <= HOUR_IN_SECONDS * 3 ) {
			return '3_hours';
		} elseif ( $diff <= DAY_IN_SECONDS ) {
			return 'day';
		} elseif ( $diff <= DAY_IN_SECONDS * 3 ) {
			return '3_days';
		} elseif ( $diff <= WEEK_IN_SECONDS ) {
			return 'week';
		} elseif ( $diff <= MONTH_IN_SECONDS ) {
			return 'month';
		} else {
			return 'custom';
		}
	}

	/**
	 * AJAX: Export Logs
	 *
	 * @since 1.0.0
	 * @return void
	 */
	public function ajaxExportLogs(): void {
		$this->verifyAjaxNonce();

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'Permission denied.', 'wp-powersuite' ) );
		}

		$login_id = isset( $_GET['login_id'] ) ? absint( $_GET['login_id'] ) : 0;
		$logs = $this->getActivityLogs(
			[
				'login_id'      => $login_id ?: null,
				'exclude_noise' => true,
			]
		);

		header( 'Content-Type: text/csv' );
		header( 'Content-Disposition: attachment; filename="temporary-login-logs-' . date( 'Y-m-d' ) . '.csv"' );

		$output = fopen( 'php://output', 'w' );
		fputcsv( $output, [ 'ID', 'Login ID', 'User ID', 'Action', 'IP Address', 'User Agent', 'Page Accessed', 'Logged At' ] );

		foreach ( $logs as $log ) {
			fputcsv(
				$output,
				[
					$log->id,
					$log->login_id,
					$log->user_id,
					$log->action,
					$log->ip_address,
					$log->user_agent,
					$log->page_accessed,
					$log->logged_at,
				]
			);
		}

		fclose( $output );
		exit;
	}

	/**
	 * Get Login URL
	 *
	 * Gets the login URL for a token.
	 *
	 * @since 1.0.0
	 * @param string $token Token.
	 * @return string Login URL.
	 */
	public function getLoginUrl( string $plain_token ): string {
		return add_query_arg( self::TOKEN_PARAM, $plain_token, home_url() );
	}

}
