<?php

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

class UserMorph_User_Links
{

    public function __construct()
    {
        add_filter('user_row_actions', array($this, 'add_user_row_actions'), 10, 2);
        add_action('edit_user_profile', array($this, 'add_profile_switch_button'));
        add_action('show_user_profile', array($this, 'add_profile_switch_button')); // For own profile? Usually you don't switch to yourself, but standard consistent hook.
    }

    /**
     * Add "Switch To" link in Users list table
     */
    public function add_user_row_actions($actions, $user_object)
    {
        // Cannot switch to yourself
        if ($user_object->ID === get_current_user_id()) {
            return $actions;
        }

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

        // Super Admins can switch to anyone. Admins can switch to anyone.
        // Standard check: can I edit this user?
        if (!current_user_can('edit_user', $user_object->ID)) {
            return $actions;
        }

        $switch_url = add_query_arg(array(
            'usermorph_action' => 'switch_to',
            'user_id' => $user_object->ID,
            '_wpnonce' => wp_create_nonce('usermorph_switch_to_' . $user_object->ID)
        ), site_url());

        $actions['usermorph_switch'] = '<a href="' . esc_url($switch_url) . '">Switch To</a>';

        return $actions;
    }

    /**
     * Add "Switch To" button in User Profile screen
     */
    public function add_profile_switch_button($user_object)
    {
        if ($user_object->ID === get_current_user_id()) {
            return;
        }

        if (!current_user_can('edit_users') || !current_user_can('edit_user', $user_object->ID)) {
            return;
        }

        $switch_url = add_query_arg(array(
            'advus_action' => 'switch_to',
            'user_id' => $user_object->ID,
            '_wpnonce' => wp_create_nonce('advus_switch_to_' . $user_object->ID)
        ), site_url());

        ?>
        <table class="form-table">
            <tr>
                <th><label>User Switching</label></th>
                <td>
                    <a href="<?php echo esc_url($switch_url); ?>" class="button button-secondary">Switch To
                        <?php echo esc_html($user_object->display_name); ?></a>
                </td>
            </tr>
        </table>
        <?php
    }
}

new UserMorph_User_Links();
