<?php

/*
* User switch related hooks code starts
* Add "Switch User" to admin bar under current user menu
*/

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

add_action('admin_bar_menu', 'sapmfly_admin_bar_switch_user_menu', 999);
function sapmfly_admin_bar_switch_user_menu($wp_admin_bar)
{
    if (get_option('sapmfly_user_switching') !== 'yes') {
        return;
    }

    // Only admins can switch
    if (!current_user_can('manage_options')) {
        return;
    }

    // Add under WP built-in user menu
    $wp_admin_bar->add_node([
        'id'     => 'sapmfly-switch-user-menu',
        'parent' => 'my-account',
        'title'  => '🔄 Switch User',
        'href'   => admin_url('users.php'),
    ]);

    // Show Back to Admin if original admin meta exists
    $current_user = wp_get_current_user();
    $original_admin_id = get_user_meta($current_user->ID, '_sapmfly_original_admin', true);

    if ($original_admin_id && !user_can($current_user, 'manage_options')) {
        $nonce = wp_create_nonce('sapmfly_back_admin_' . $original_admin_id);
        $back_url = add_query_arg([
            'sapmfly_back_admin' => $original_admin_id,
            'nonce'              => $nonce
        ], admin_url());

        $wp_admin_bar->add_node([
            'id'     => 'sapmfly-back-to-admin',
            'parent' => 'my-account',
            'title'  => '⬅ Back to Admin',
            'href'   => esc_url($back_url),
        ]);
    }
}

/**
 * Add "Switch" link to user row actions
 */
add_filter('user_row_actions', 'sapmfly_user_switch_row_action', 10, 2);
function sapmfly_user_switch_row_action($actions, $user_object)
{
    $enable_user_switching = get_option('sapmfly_user_switching');

    if ($enable_user_switching !== 'yes') {
        return $actions;
    }

    if (!current_user_can('manage_options')) {
        return $actions;
    }

    if ($user_object->ID == get_current_user_id()) {
        return $actions;
    }

    $nonce = wp_create_nonce('sapmfly_user_switch_' . $user_object->ID);

    $switch_url = add_query_arg([
        'sapmfly_switch_user' => $user_object->ID,
        'nonce'               => $nonce
    ], admin_url());

    $actions['sapmfly_switch'] = '<a href="' . esc_url($switch_url) . '">Switch me here</a>';

    return $actions;
}

/**
 * Handle switching to another user
 */
add_action('admin_init', 'sapmfly_handle_user_switch');

function sapmfly_handle_user_switch() {

    if ( ! isset( $_GET['sapmfly_switch_user'] ) ) {
        return;
    }

    $enable_user_switching = get_option( 'sapmfly_user_switching' );
    $user_id               = absint( $_GET['sapmfly_switch_user'] );

    if ( 'yes' !== $enable_user_switching ) {
        wp_die( esc_html__( 'User switching disabled.', 'minifly' ) );
    }

    if ( ! current_user_can( 'manage_options' ) ) {
        wp_die( esc_html__( 'No permission.', 'minifly' ) );
    }

    if (
        ! isset( $_GET['nonce'] ) ||
        ! wp_verify_nonce(
            sanitize_text_field( wp_unslash( $_GET['nonce'] ) ),
            'sapmfly_user_switch_' . $user_id
        )
    ) {
        wp_die( esc_html__( 'Invalid nonce.', 'minifly' ) );
    }

    $userdata = get_userdata( $user_id );

    if ( ! $userdata ) {
        wp_die( esc_html__( 'User not found.', 'minifly' ) );
    }

    // Save original admin ID if not already saved
    if ( ! get_user_meta( get_current_user_id(), '_sapmfly_original_admin', true ) ) {
        update_user_meta(
            get_current_user_id(),
            '_sapmfly_original_admin',
            get_current_user_id()
        );
    }

    wp_set_current_user( $user_id );
    wp_set_auth_cookie( $user_id );

    wp_safe_redirect( admin_url() );
    exit;
}

/**
 * Handle Back to Admin action
 */
add_action( 'admin_init', 'sapmfly_handle_back_to_admin' );

function sapmfly_handle_back_to_admin() {

    if ( ! isset( $_GET['sapmfly_back_admin'] ) ) {
        return;
    }

    $current_user       = wp_get_current_user();
    $original_admin_id  = get_user_meta(
        $current_user->ID,
        '_sapmfly_original_admin',
        true
    );

    if ( ! $original_admin_id ) {
        wp_die( esc_html__( 'Cannot switch back.', 'minifly' ) );
    }

    // Verify nonce
    if (
        ! isset( $_GET['nonce'] ) ||
        ! wp_verify_nonce(
            sanitize_text_field( wp_unslash( $_GET['nonce'] ) ),
            'sapmfly_back_admin_' . $original_admin_id
        )
    ) {
        wp_die( esc_html__( 'Invalid nonce.', 'minifly' ) );
    }

    // Prevent switching if already admin
    if ( user_can( $current_user, 'manage_options' ) ) {
        wp_die( esc_html__( 'Already administrator.', 'minifly' ) );
    }

    // Ensure original admin still exists
    $admin_user = get_userdata( $original_admin_id );

    if ( ! $admin_user || ! user_can( $admin_user, 'manage_options' ) ) {
        wp_die( esc_html__( 'Original admin not found.', 'minifly' ) );
    }

    delete_user_meta( $current_user->ID, '_sapmfly_original_admin' );

    wp_set_current_user( $original_admin_id );
    wp_set_auth_cookie( $original_admin_id );

    wp_safe_redirect( admin_url() );
    exit;
}