<?php
/**
 * Temporary Login Admin Interface
 *
 * Admin UI for managing temporary logins.
 *
 * @package TemporaryLogin
 * @since 1.0.0
 */

use TemporaryLogin\FeatureGate;
use WP_PowerSuite\Core\OptionStore;

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

require_once __DIR__ . '/FeatureGate.php';

if ( ! current_user_can( 'manage_options' ) ) {
	wp_die( esc_html__( 'You do not have sufficient permissions to access this page.', 'wp-powersuite' ) );
}

if ( ! isset( $module_id ) || empty( $module_id ) ) {
	$module_id = 'temporary-login';
}

$premium_unlocked = FeatureGate::isPremiumLicensed();
$license_page_url = admin_url( 'admin.php?page=powersuite-license' );
$free_expiry_type   = FeatureGate::FREE_EXPIRY_TYPE;

$tl_expiry_options = [
	'hour'      => __( '1 Hour', 'wp-powersuite' ),
	'3_hours'   => __( '3 Hours', 'wp-powersuite' ),
	'day'       => __( '1 Day', 'wp-powersuite' ),
	'3_days'    => __( '3 Days', 'wp-powersuite' ),
	'week'      => __( '1 Week', 'wp-powersuite' ),
	'month'     => __( '1 Month', 'wp-powersuite' ),
	'custom'    => __( 'Custom Date & Time', 'wp-powersuite' ),
];

$module_class = 'TemporaryLogin\\Module';
if ( ! class_exists( $module_class ) ) {
	echo '<div class="notice notice-error"><p>' . esc_html__( 'Temporary Login module class not found.', 'wp-powersuite' ) . '</p></div>';
	return;
}

$module = null;
if ( class_exists( 'WP_PowerSuite\\Core\\ModuleManager' ) ) {
	$module_manager = \WP_PowerSuite\Core\ModuleManager::getInstance();
	$module = $module_manager->getModule( 'temporary-login' );
}

// Fallback to creating new instance
if ( ! $module ) {
	$module = new $module_class();
}

// Base URL for this page (standalone page; filter links must use this)
$tl_page_url = admin_url( 'admin.php?page=powersuite-temporary-login' );
$status      = isset( $_GET['status'] ) ? sanitize_text_field( $_GET['status'] ) : 'all';
if ( ! in_array( $status, [ 'all', 'active', 'expired', 'revoked' ], true ) ) {
	$status = 'all';
}

// Process bulk actions (like Posts/Pages table)
$bulk_nonce = isset( $_POST['_wpnonce'] ) ? sanitize_text_field( wp_unslash( $_POST['_wpnonce'] ) ) : '';
$bulk_action = isset( $_POST['action'] ) && $_POST['action'] !== '-1' ? sanitize_text_field( wp_unslash( $_POST['action'] ) ) : ( isset( $_POST['action2'] ) && $_POST['action2'] !== '-1' ? sanitize_text_field( wp_unslash( $_POST['action2'] ) ) : '' );
$bulk_ids = isset( $_POST['login'] ) && is_array( $_POST['login'] ) ? array_map( 'absint', wp_unslash( $_POST['login'] ) ) : [];
$bulk_ids = array_filter( $bulk_ids );

if ( $bulk_action && ! empty( $bulk_ids ) && wp_verify_nonce( $bulk_nonce, 'bulk-logins' ) && current_user_can( 'manage_options' ) ) {
	$done = 0;
	$errors = 0;
	foreach ( $bulk_ids as $login_id ) {
		switch ( $bulk_action ) {
			case 'delete':
				if ( method_exists( $module, 'deleteLogin' ) && $module->deleteLogin( $login_id ) ) {
					$done++;
				} else {
					$errors++;
				}
				break;
			case 'revoke':
				if ( method_exists( $module, 'revokeLogin' ) && $module->revokeLogin( $login_id ) ) {
					$done++;
				} else {
					$errors++;
				}
				break;
			case 'enable':
				if ( method_exists( $module, 'enableLogin' ) && $module->enableLogin( $login_id ) ) {
					$done++;
				} else {
					$errors++;
				}
				break;
			case 'expire':
				if ( method_exists( $module, 'expireLogin' ) && $module->expireLogin( $login_id ) ) {
					$done++;
				} else {
					$errors++;
				}
				break;
		}
	}
	$redirect = add_query_arg( 'page', 'powersuite-temporary-login', admin_url( 'admin.php' ) );
	$redirect = add_query_arg( 'status', $status, $redirect );
	if ( $done > 0 ) {
		$redirect = add_query_arg( 'tl_done', $done . '_' . $bulk_action, $redirect );
	}
	if ( $errors > 0 ) {
		$redirect = add_query_arg( 'tl_errors', $errors, $redirect );
	}
	wp_safe_redirect( $redirect );
	exit;
}

// Roles for the form
$wp_roles = wp_roles();
$roles    = $wp_roles->get_names();

// Counts for filter links (single query)
$counts        = method_exists( $module, 'getLoginCounts' ) ? $module->getLoginCounts() : [ 'all' => 0, 'active' => 0, 'expired' => 0, 'revoked' => 0 ];
$count_all     = (int) $counts['all'];
$count_active  = (int) $counts['active'];
$count_expired = (int) $counts['expired'];
$count_revoked = (int) $counts['revoked'];

require_once __DIR__ . '/class-temporary-login-list-table.php';
$list_table = new Temporary_Login_List_Table( $module, $status );
$list_table->prepare_items();
?>

<?php
$tl_done   = isset( $_GET['tl_done'] ) ? sanitize_text_field( wp_unslash( $_GET['tl_done'] ) ) : '';
$tl_errors = isset( $_GET['tl_errors'] ) ? absint( $_GET['tl_errors'] ) : 0;
if ( $tl_done !== '' ) {
	$parts = explode( '_', $tl_done, 2 );
	$num   = isset( $parts[0] ) ? absint( $parts[0] ) : 0;
	$act   = isset( $parts[1] ) ? $parts[1] : '';
	$labels = [
		'delete' => __( 'deleted', 'wp-powersuite' ),
		'revoke' => __( 'revoked', 'wp-powersuite' ),
		'enable' => __( 'enabled', 'wp-powersuite' ),
		'expire' => __( 'expired', 'wp-powersuite' ),
	];
	$label = $labels[ $act ] ?? $act;
	if ( $num > 0 ) {
		echo '<div class="notice notice-success is-dismissible"><p>' . esc_html( sprintf( _n( '%1$d login %2$s.', '%1$d logins %2$s.', $num, 'wp-powersuite' ), $num, $label ) ) . '</p></div>';
	}
	if ( $tl_errors > 0 ) {
		echo '<div class="notice notice-warning is-dismissible"><p>' . esc_html( sprintf( _n( '%d item could not be updated.', '%d items could not be updated.', $tl_errors, 'wp-powersuite' ), $tl_errors ) ) . '</p></div>';
	}
}
?>

<div class="wrap">
	<hr class="wp-header-end">
	<?php
	\WP_PowerSuite\Admin\PageHero::render_for_module(
		[
			'icon'      => 'dashicons-clock',
			'title'     => __( 'Temporary Login Manager', 'wp-powersuite' ),
			'tagline'   => __( 'Create time-limited admin logins without sharing your main account password.', 'wp-powersuite' ),
			'meta_html' => '<a href="#" class="button button-primary" id="tl-create-login-btn">' . esc_html__( 'Create New Login', 'wp-powersuite' ) . '</a>',
		]
	);
	?>

	<!-- Top notice: all messages except login-link success (errors, copy confirmation, revoke/delete/enable failures, etc.) -->
	<div id="tl-notice-top" class="notice notice-success" style="display: none; margin: 0 0 15px;">
		<p id="tl-notice-top-message"></p>
	</div>

	<div class="wp-powersuite-module-settings">
		<div class="notice notice-info" style="margin: 12px 0;">
			<p>
				<?php esc_html_e( 'Share links only with the intended recipient. Token links bypass two-factor authentication when that module is enabled. Existing WordPress accounts keep their normal password login—use a new email address to create a link-only user when you need to avoid password access.', 'wp-powersuite' ); ?>
			</p>
		</div>
		<!-- Filters (like Posts/Pages subsubsub) -->
		<ul class="subsubsub">
			<li>
				<a href="<?php echo esc_url( add_query_arg( 'status', 'all', $tl_page_url ) ); ?>" class="<?php echo $status === 'all' ? 'current' : ''; ?>">
					<?php esc_html_e( 'All', 'wp-powersuite' ); ?>
					<span class="count">(<?php echo (int) $count_all; ?>)</span>
				</a> |
			</li>
			<li>
				<a href="<?php echo esc_url( add_query_arg( 'status', 'active', $tl_page_url ) ); ?>" class="<?php echo $status === 'active' ? 'current' : ''; ?>">
					<?php esc_html_e( 'Active', 'wp-powersuite' ); ?>
					<span class="count">(<?php echo (int) $count_active; ?>)</span>
				</a> |
			</li>
			<li>
				<a href="<?php echo esc_url( add_query_arg( 'status', 'expired', $tl_page_url ) ); ?>" class="<?php echo $status === 'expired' ? 'current' : ''; ?>">
					<?php esc_html_e( 'Expired', 'wp-powersuite' ); ?>
					<span class="count">(<?php echo (int) $count_expired; ?>)</span>
				</a> |
			</li>
			<li>
				<a href="<?php echo esc_url( add_query_arg( 'status', 'revoked', $tl_page_url ) ); ?>" class="<?php echo $status === 'revoked' ? 'current' : ''; ?>">
					<?php esc_html_e( 'Revoked', 'wp-powersuite' ); ?>
					<span class="count">(<?php echo (int) $count_revoked; ?>)</span>
				</a>
			</li>
		</ul>

		<!-- Standard WordPress list table with bulk actions (like Posts/Pages) -->
		<form method="post" id="tl-list-form">
			<input type="hidden" name="page" value="powersuite-temporary-login" />
			<?php wp_nonce_field( 'bulk-logins', '_wpnonce', false ); ?>
			<?php $list_table->display(); ?>
		</form>

	<!-- Create/Edit form inline (no modal) -->
	<div id="tl-create-edit-form" class="postbox" style="margin-top: 20px;">
		<div class="postbox-header" style="align-items: center;">
			<h2 class="hndle ui-sortable-handle" style="margin: 0; padding: 12px 20px; font-size: 14px; font-weight: 600; line-height: 1.4;"><span id="tl-form-title-text"><?php esc_html_e( 'Create Temporary Login', 'wp-powersuite' ); ?></span></h2>
		</div>
		<div class="inside" style="padding: 20px;">
			<form id="tl-login-form" class="tl-form">
				<?php wp_nonce_field( 'tl_nonce', 'tl_nonce_field' ); ?>
				<input type="hidden" id="tl-login-id" name="login_id" value="0">

				<table class="form-table" role="presentation">
					<tbody>
						<tr>
							<th scope="row">
								<label for="tl-user-select"><?php esc_html_e( 'Select User', 'wp-powersuite' ); ?></label>
							</th>
							<td>
								<input type="hidden" id="tl-user-id" name="user_id" value="">
								<input type="text" id="tl-user-search" class="regular-text" autocomplete="off" placeholder="<?php esc_attr_e( 'Search users by name, login, or email…', 'wp-powersuite' ); ?>">
								<div id="tl-user-search-results" class="tl-user-search-results" role="listbox" hidden></div>
								<p id="tl-user-selected" class="description" style="display:none;"></p>
								<p class="description"><?php esc_html_e( 'Or enter email below to create a new user.', 'wp-powersuite' ); ?></p>
							</td>
						</tr>
						<tr>
							<th scope="row">
								<label for="tl-user-email"><?php esc_html_e( 'Or Email Address', 'wp-powersuite' ); ?></label>
							</th>
							<td>
								<input type="email" id="tl-user-email" name="email" class="regular-text" placeholder="user@example.com">
								<p class="description"><?php esc_html_e( 'New users are created as subscribers in WordPress; the role selected here applies only for the temporary session.', 'wp-powersuite' ); ?></p>
							</td>
						</tr>
						<tr>
							<th scope="row">
								<label for="tl-role"><?php esc_html_e( 'Role', 'wp-powersuite' ); ?></label>
							</th>
							<td>
								<select id="tl-role" name="role" class="regular-text">
									<?php foreach ( $roles as $role_key => $role_name ) : ?>
										<option value="<?php echo esc_attr( $role_key ); ?>" <?php selected( $role_key, 'subscriber' ); ?>>
											<?php echo esc_html( $role_name ); ?>
										</option>
									<?php endforeach; ?>
								</select>
							</td>
						</tr>
						<tr>
							<th scope="row">
								<label for="tl-expiry-type"><?php esc_html_e( 'Expiry', 'wp-powersuite' ); ?></label>
							</th>
							<td>
								<select id="tl-expiry-type" name="expiry_type" class="regular-text" <?php echo $premium_unlocked ? '' : 'data-tl-free-tier="1"'; ?>>
									<?php foreach ( $tl_expiry_options as $expiry_key => $expiry_label ) : ?>
										<?php
										$is_free_option = $expiry_key === $free_expiry_type;
										$option_selected = $expiry_key === $free_expiry_type;
										?>
										<option
											value="<?php echo esc_attr( $expiry_key ); ?>"
											<?php selected( $option_selected ); ?>
											<?php disabled( ! $premium_unlocked && ! $is_free_option ); ?>
										><?php echo esc_html( $expiry_label ); ?><?php echo ( ! $premium_unlocked && ! $is_free_option ) ? ' (' . esc_html__( 'Premium', 'wp-powersuite' ) . ')' : ''; ?></option>
									<?php endforeach; ?>
								</select>
								<?php if ( ! $premium_unlocked ) : ?>
									<p class="description">
										<?php
										echo wp_kses_post(
											sprintf(
												/* translators: %s: URL to license page */
												__( 'Free plan: 1-day expiry only. <a href="%s">Activate your license</a> for longer durations and custom dates.', 'wp-powersuite' ),
												esc_url( $license_page_url )
											)
										);
										?>
									</p>
								<?php endif; ?>
							</td>
						</tr>
						<tr id="tl-custom-date-row" style="display: none;">
							<th scope="row">
								<label for="tl-expiry-date"><?php esc_html_e( 'Custom Expiry', 'wp-powersuite' ); ?> <?php if ( ! $premium_unlocked ) : ?><span class="wpps-pro-badge"><?php esc_html_e( 'Premium', 'wp-powersuite' ); ?></span><?php endif; ?></label>
							</th>
							<td>
								<input type="datetime-local" id="tl-expiry-date" name="expiry_date" class="regular-text" <?php disabled( ! $premium_unlocked ); ?>>
							</td>
						</tr>
						<tr>
							<th scope="row">
								<label for="tl-single-use"><?php esc_html_e( 'Single Use', 'wp-powersuite' ); ?> <?php if ( ! $premium_unlocked ) : ?><span class="wpps-pro-badge"><?php esc_html_e( 'Premium', 'wp-powersuite' ); ?></span><?php endif; ?></label>
							</th>
							<td>
								<label>
									<input type="checkbox" id="tl-single-use" name="single_use" value="1" <?php disabled( ! $premium_unlocked ); ?>>
									<?php esc_html_e( 'Link can only be used once', 'wp-powersuite' ); ?>
								</label>
							</td>
						</tr>
						<tr>
							<th scope="row">
								<label for="tl-max-uses"><?php esc_html_e( 'Maximum Uses', 'wp-powersuite' ); ?> <?php if ( ! $premium_unlocked ) : ?><span class="wpps-pro-badge"><?php esc_html_e( 'Premium', 'wp-powersuite' ); ?></span><?php endif; ?></label>
							</th>
							<td>
								<input type="number" id="tl-max-uses" name="max_uses" value="0" min="0" class="small-text" <?php disabled( ! $premium_unlocked ); ?>>
								<p class="description"><?php esc_html_e( 'Set to 0 for unlimited.', 'wp-powersuite' ); ?></p>
							</td>
						</tr>
						<tr>
							<th scope="row">
								<label for="tl-ip-restriction"><?php esc_html_e( 'IP Restriction', 'wp-powersuite' ); ?> <?php if ( ! $premium_unlocked ) : ?><span class="wpps-pro-badge"><?php esc_html_e( 'Premium', 'wp-powersuite' ); ?></span><?php endif; ?></label>
							</th>
							<td>
								<input type="text" id="tl-ip-restriction" name="ip_restriction" class="regular-text" placeholder="192.168.1.1 or 192.168.1.0/24" <?php disabled( ! $premium_unlocked ); ?>>
								<p class="description"><?php esc_html_e( 'Optional: Restrict to specific IP or CIDR range.', 'wp-powersuite' ); ?></p>
							</td>
						</tr>
						<tr>
							<th scope="row">
								<label for="tl-bind-user-agent"><?php esc_html_e( 'Device Binding', 'wp-powersuite' ); ?> <?php if ( ! $premium_unlocked ) : ?><span class="wpps-pro-badge"><?php esc_html_e( 'Premium', 'wp-powersuite' ); ?></span><?php endif; ?></label>
							</th>
							<td>
								<label>
									<input type="checkbox" id="tl-bind-user-agent" name="bind_user_agent" value="1" <?php disabled( ! $premium_unlocked ); ?>>
									<?php esc_html_e( 'Bind to first device (prevents link sharing)', 'wp-powersuite' ); ?>
								</label>
							</td>
						</tr>
						<tr id="tl-plugin-theme-row" style="display: none;">
							<th scope="row"><?php esc_html_e( 'Plugin & theme access', 'wp-powersuite' ); ?></th>
							<td>
								<fieldset>
									<label style="display:block;margin-bottom:6px;">
										<input type="checkbox" id="tl-install-plugins" name="install_plugins" value="1">
										<?php esc_html_e( 'Allow installing and activating plugins', 'wp-powersuite' ); ?>
									</label>
									<label style="display:block;margin-bottom:6px;">
										<input type="checkbox" id="tl-delete-plugins" name="delete_plugins" value="1">
										<?php esc_html_e( 'Allow deactivating and deleting plugins', 'wp-powersuite' ); ?>
									</label>
									<label style="display:block;margin-bottom:6px;">
										<input type="checkbox" id="tl-install-themes" name="install_themes" value="1">
										<?php esc_html_e( 'Allow installing and activating themes', 'wp-powersuite' ); ?>
									</label>
									<label style="display:block;margin-bottom:6px;">
										<input type="checkbox" id="tl-delete-themes" name="delete_themes" value="1">
										<?php esc_html_e( 'Allow deleting themes', 'wp-powersuite' ); ?>
									</label>
								</fieldset>
								<p class="description"><?php esc_html_e( 'Unchecked by default. WP PowerSuite cannot be deactivated or removed. Plugin/theme file editors and core updates are always blocked.', 'wp-powersuite' ); ?></p>
							</td>
						</tr>
						<tr>
							<th scope="row">
								<label for="tl-redirect-to"><?php esc_html_e( 'Redirect After Login', 'wp-powersuite' ); ?></label>
							</th>
							<td>
								<input type="url" id="tl-redirect-to" name="redirect_to" class="regular-text" placeholder="<?php echo esc_attr( admin_url() ); ?>">
								<p class="description"><?php esc_html_e( 'Optional: URL to redirect to after login.', 'wp-powersuite' ); ?></p>
							</td>
						</tr>
					</tbody>
				</table>
			</form>
			<p class="submit">
				<button type="button" class="button" id="tl-form-cancel-btn"><?php esc_html_e( 'Cancel', 'wp-powersuite' ); ?></button>
				<button type="button" class="button button-primary" id="tl-save-login-btn"><?php esc_html_e( 'Create Login', 'wp-powersuite' ); ?></button>
			</p>
		</div>
	</div>

	<!-- Activity Logs modal -->
	<div id="tl-logs-modal" class="tl-modal" style="display: none;" aria-hidden="true">
		<div class="tl-modal__overlay"></div>
		<div class="tl-modal__box" role="dialog" aria-labelledby="tl-logs-modal-title">
			<div class="tl-modal__header">
				<h2 id="tl-logs-modal-title" class="tl-modal__title"><?php esc_html_e( 'Activity Logs', 'wp-powersuite' ); ?></h2>
				<div class="tl-modal__header-actions">
					<button type="button" class="button button-primary" id="tl-export-logs-btn"><?php esc_html_e( 'Export CSV', 'wp-powersuite' ); ?></button>
					<button type="button" class="tl-modal__close" id="tl-logs-close-btn" aria-label="<?php esc_attr_e( 'Close', 'wp-powersuite' ); ?>">&times;</button>
				</div>
			</div>
			<div class="tl-modal__body">
				<div id="tl-logs-content">
					<p style="text-align: center; padding: 20px;">
						<span class="spinner is-active"></span>
						<?php esc_html_e( 'Loading logs...', 'wp-powersuite' ); ?>
					</p>
				</div>
			</div>
		</div>
	</div>

	<!-- Success/error notice at bottom of page (with link + Copy + Refresh when login created). Placed last so it never appears at top. -->
	<div id="tl-notice" class="tl-notice-box" style="display: none; margin: 20px 0 0; padding: 12px 20px; border-left: 4px solid #00a32a; background: #fff; box-shadow: 0 1px 1px rgba(0,0,0,.04);">
		<p id="tl-notice-message" style="margin: 0 0 10px;"></p>
		<div id="tl-notice-link-row" style="display: none; margin-top: 10px;">
			<label for="tl-info-link-input" style="display: block; margin-bottom: 4px; font-weight: 600;"><?php esc_html_e( 'Login Link:', 'wp-powersuite' ); ?></label>
			<div style="display: flex; gap: 8px; align-items: center; flex-wrap: wrap;">
				<input type="text" id="tl-info-link-input" class="regular-text" readonly style="flex: 1; min-width: 200px; max-width: 500px;">
				<button type="button" class="button" id="tl-info-copy-btn"><?php esc_html_e( 'Copy', 'wp-powersuite' ); ?></button>
				<a href="<?php echo esc_url( $tl_page_url ); ?>" class="button" id="tl-notice-refresh-btn"><?php esc_html_e( 'Refresh', 'wp-powersuite' ); ?></a>
			</div>
		</div>
	</div>
	</div>
</div>
