<?php
/**
 * Login As User / Impersonation functionality for Clicks User Manager.
 *
 * @package WP_User_Management
 */

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

/**
 * Hook switch-back check on init and render float bar.
 */
add_action( 'init', 'wpum_check_impersonation_actions' );
add_action( 'wp_footer', 'wpum_render_impersonation_bar' );
add_action( 'admin_footer', 'wpum_render_impersonation_bar' );

/**
 * Handle switch-back and login-as actions.
 */
function wpum_check_impersonation_actions() {
	// 1. Switch back action
	if ( isset( $_GET['wpum_action'] ) && 'switch_back' === $_GET['wpum_action'] ) {
		$original_admin_id = isset( $_COOKIE['wpum_imp_admin'] ) ? absint( $_COOKIE['wpum_imp_admin'] ) : 0;
		$token             = isset( $_COOKIE['wpum_imp_token'] ) ? sanitize_key( $_COOKIE['wpum_imp_token'] ) : '';
		$saved_token       = get_transient( 'wpum_imp_' . $original_admin_id );

		if ( $original_admin_id && $token && $token === $saved_token ) {
			// Clear current session
			wp_destroy_current_session();
			wp_clear_auth_cookie();

			// Login back as admin
			wp_set_current_user( $original_admin_id );
			wp_set_auth_cookie( $original_admin_id, true );

			// Clean up cookies & transients
			delete_transient( 'wpum_imp_' . $original_admin_id );
			setcookie( 'wpum_imp_admin', '', time() - YEAR_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN );
			setcookie( 'wpum_imp_token', '', time() - YEAR_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN );

			// Redirect back to user manager dashboard
			wp_safe_redirect( admin_url( 'admin.php?page=clicks-user-manager&wpum_notice=switched_back' ) );
			exit;
		}
	}

	// 2. Login-as trigger action (needs privilege checks)
	if ( isset( $_GET['wpum_action'] ) && 'login_as' === $_GET['wpum_action'] ) {
		if ( ! isset( $_GET['_wpnonce'] ) || ! wp_verify_nonce( $_GET['_wpnonce'], 'wpum_login_as_nonce' ) ) {
			wp_die( esc_html__( 'Security check failed.', 'clicks-user-manager' ) );
		}

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'Permission denied.', 'clicks-user-manager' ) );
		}

		$user_id = isset( $_GET['user_id'] ) ? absint( $_GET['user_id'] ) : 0;
		$target_user = get_userdata( $user_id );

		if ( ! $target_user ) {
			wp_die( esc_html__( 'User not found.', 'clicks-user-manager' ) );
		}

		$admin_id = get_current_user_id();

		if ( $admin_id === $target_user->ID ) {
			wp_die( esc_html__( 'You cannot impersonate yourself.', 'clicks-user-manager' ) );
		}

		// Enforce Free limit of 3 impersonations per month
		if ( ! wpum_is_pro() ) {
			$current_month = gmdate( 'Y_m' );
			$limit_key     = '_wpum_imp_count_' . $current_month;
			$current_count = absint( get_option( $limit_key, 0 ) );

			if ( $current_count >= 3 ) {
				// Redirect with error
				wp_safe_redirect( admin_url( 'admin.php?page=clicks-user-manager&wpum_error=imp_limit' ) );
				exit;
			}

			// Increment count
			update_option( $limit_key, $current_count + 1 );
		}

		// Perform switch
		wp_destroy_current_session();
		wp_clear_auth_cookie();

		// Log in as target
		wp_set_current_user( $target_user->ID );
		wp_set_auth_cookie( $target_user->ID, true );

		// Set cookie & transient credentials
		$token = wp_generate_password( 32, false );
		setcookie( 'wpum_imp_admin', $admin_id, 0, COOKIEPATH, COOKIE_DOMAIN, is_ssl(), true );
		setcookie( 'wpum_imp_token', $token, 0, COOKIEPATH, COOKIE_DOMAIN, is_ssl(), true );
		set_transient( 'wpum_imp_' . $admin_id, $token, 12 * HOUR_IN_SECONDS );

		// Redirect to site home page to see from user's perspective
		wp_safe_redirect( home_url() );
		exit;
	}
}

/**
 * Check if the current session is an impersonation session.
 *
 * @return bool True if impersonating.
 */
function wpum_is_impersonating() {
	$original_admin_id = isset( $_COOKIE['wpum_imp_admin'] ) ? absint( $_COOKIE['wpum_imp_admin'] ) : 0;
	$token             = isset( $_COOKIE['wpum_imp_token'] ) ? sanitize_key( $_COOKIE['wpum_imp_token'] ) : '';
	if ( ! $original_admin_id || ! $token ) {
		return false;
	}
	$saved_token = get_transient( 'wpum_imp_' . $original_admin_id );
	return $saved_token && $token === $saved_token;
}

/**
 * Render the Switch Back floating bar in footers.
 */
function wpum_render_impersonation_bar() {
	if ( ! wpum_is_impersonating() ) {
		return;
	}

	$current_user = wp_get_current_user();
	$switch_back_url = add_query_arg( array( 'wpum_action' => 'switch_back' ), home_url() );
	?>
	<div id="wpum-impersonation-bar" style="position: fixed; top: 0; left: 0; right: 0; background: #d63638; color: #fff; text-align: center; padding: 10px; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen-Sans, Ubuntu, Cantarell, 'Helvetica Neue', sans-serif; font-size: 13px; z-index: 9999999; box-shadow: 0 2px 10px rgba(0,0,0,0.3); display: flex; justify-content: center; align-items: center; gap: 15px;">
		<span>
			<strong><?php esc_html_e( 'Clicks User Manager:', 'clicks-user-manager' ); ?></strong>
			<?php
			/* translators: %s: current username */
			printf( esc_html__( 'You are viewing the site as user "%s"', 'clicks-user-manager' ), esc_html( $current_user->user_login ) );
			?>
		</span>
		<a href="<?php echo esc_url( $switch_back_url ); ?>" style="background: #fff; color: #d63638; text-decoration: none; padding: 4px 10px; border-radius: 3px; font-weight: 600; font-size: 12px; transition: opacity 0.2s;" onmouseover="this.style.opacity=0.9" onmouseout="this.style.opacity=1">
			<?php esc_html_e( 'Switch Back to Admin', 'clicks-user-manager' ); ?>
		</a>
	</div>
	<style>
		/* Adjust body padding so floating bar doesn't overlap header */
		html {
			margin-top: 38px !important;
		}
		@media screen and (max-width: 782px) {
			html {
				margin-top: 38px !important;
			}
		}
	</style>
	<?php
}
