<?php

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

class UserMorph_Admin_Bar
{

    public function __construct()
    {
        add_action('admin_bar_menu', array($this, 'add_toolbar_items'), 100);
        add_action('admin_enqueue_scripts', array($this, 'enqueue_assets'));
        add_action('wp_enqueue_scripts', array($this, 'enqueue_assets'));

        // AJAX search
        add_action('wp_ajax_usermorph_search_users', array($this, 'ajax_search_users'));
    }

    public function enqueue_assets()
    {
        if (!is_user_logged_in()) {
            return;
        }

        if (!current_user_can('edit_users') && !isset($_COOKIE['usermorph_original_user'])) {
            return;
        }

        wp_enqueue_style('usermorph-style', USERMORPH_PLUGIN_URL . 'assets/css/style.css', array(), '1.0.0');
        wp_enqueue_script('usermorph-script', USERMORPH_PLUGIN_URL . 'assets/js/script.js', array('jquery'), '1.0.0', true);

        wp_localize_script('usermorph-script', 'usermorphVars', array(
            'ajaxurl' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('usermorph_search_nonce')
        ));
    }

    public function add_toolbar_items($admin_bar)
    {
        // 1. Check if we are in "Switched Mode"
        if (isset($_COOKIE['usermorph_original_user'])) {
            $this->add_switch_back_button($admin_bar);
        } elseif (current_user_can('edit_users')) {
            $this->add_search_bar($admin_bar);
        }
    }

    private function add_switch_back_button($admin_bar)
    {
        // Verify cookie exists before usage (although checked in caller, good practice)
        if (!isset($_COOKIE['usermorph_original_user'])) {
            return;
        }

        $original_uid = intval(wp_unslash($_COOKIE['usermorph_original_user']));
        $user_info = get_userdata($original_uid);
        $name = $user_info ? $user_info->display_name : 'Admin';

        $url = add_query_arg(array(
            'usermorph_action' => 'switch_back',
            '_wpnonce' => wp_create_nonce('usermorph_switch_back')
        ), site_url());

        $admin_bar->add_node(array(
            'id' => 'usermorph-switch-back',
            'title' => '<span class="ab-icon dashicons dashicons-undo"></span> Switch back to ' . esc_html($name),
            'href' => $url,
            'meta' => array('class' => 'usermorph-switch-back-btn')
        ));

        // Child node "Switch Off"
        $off_url = add_query_arg(array(
            'usermorph_action' => 'switch_off',
            '_wpnonce' => wp_create_nonce('usermorph_switch_off')
        ), site_url());

        $admin_bar->add_node(array(
            'id' => 'usermorph-switch-off',
            'parent' => 'usermorph-switch-back',
            'title' => 'Switch Off (Log Out)',
            'href' => $off_url,
        ));
    }

    private function add_search_bar($admin_bar)
    {
        $args = array(
            'id' => 'usermorph-switch-user',
            'title' => '<span class="ab-icon dashicons dashicons-admin-users"></span> Switch User',
            'meta' => array('class' => 'usermorph-switch-user-wrapper')
        );
        $admin_bar->add_node($args);

        // Add a custom HTML node for the search input
        $html = '
		<div class="usermorph-search-container">
			<input type="text" id="usermorph-search-input" placeholder="Search user..." autocomplete="off">
			<div id="usermorph-search-results"></div>
		</div>';

        $admin_bar->add_node(array(
            'id' => 'usermorph-search-input-node',
            'parent' => 'usermorph-switch-user',
            'title' => $html,
            'meta' => array('html' => true, 'class' => 'usermorph-search-node')
        ));
    }

    public function ajax_search_users()
    {
        check_ajax_referer('usermorph_search_nonce', 'nonce');

        if (!current_user_can('edit_users')) {
            wp_send_json_error();
        }

        // Fix: Unslash before sanitizing
        $term = isset($_POST['term']) ? sanitize_text_field(wp_unslash($_POST['term'])) : '';

        if (empty($term)) {
            wp_send_json_error();
        }

        $users = get_users(array(
            'search' => '*' . $term . '*',
            'number' => 10,
            'fields' => array('ID', 'display_name', 'user_email')
        ));

        $results = array();
        foreach ($users as $user) {
            $switch_url = add_query_arg(array(
                'usermorph_action' => 'switch_to',
                'user_id' => $user->ID,
                '_wpnonce' => wp_create_nonce('usermorph_switch_to_' . $user->ID)
            ), site_url());

            $results[] = array(
                'id' => $user->ID,
                'name' => $user->display_name . ' (' . $user->user_email . ')',
                'url' => $switch_url
            );
        }

        wp_send_json_success($results);
    }
}

new UserMorph_Admin_Bar();
