<?php

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

trait Niwa_AI_Tools_Users {

    // ==================== HELPERS ====================

    /**
     * Format a WP_User object into a standardized array.
     *
     * @param WP_User $user  WordPress user object.
     * @param bool    $full  Whether to include extended fields (bio, post count, etc.).
     * @return array
     */
    private function format_user_data( $user, $full = false ) {
        $data = array(
            'id'              => $user->ID,
            'username'        => $user->user_login,
            'email'           => $user->user_email,
            'display_name'    => $user->display_name,
            'roles'           => array_values( (array) $user->roles ),
            'registered_date' => $user->user_registered,
        );

        if ( $full ) {
            $data['first_name']  = get_user_meta( $user->ID, 'first_name', true );
            $data['last_name']   = get_user_meta( $user->ID, 'last_name', true );
            $data['nickname']    = get_user_meta( $user->ID, 'nickname', true );
            $data['description'] = get_user_meta( $user->ID, 'description', true );
            $data['url']         = $user->user_url;
            $data['post_count']  = count_user_posts( $user->ID );
        }

        return $data;
    }

    /**
     * Capture all restorable user fields for rollback.
     *
     * @param WP_User $user  WordPress user object.
     * @return array  Rollback entry data with all previous_ fields.
     */
    private function build_user_restore_entry( $user ) {
        return array(
            'type'                  => 'user_restore',
            'user_id'              => $user->ID,
            'previous_email'       => $user->user_email,
            'previous_first_name'  => get_user_meta( $user->ID, 'first_name', true ),
            'previous_last_name'   => get_user_meta( $user->ID, 'last_name', true ),
            'previous_display_name' => $user->display_name,
            'previous_nickname'    => get_user_meta( $user->ID, 'nickname', true ),
            'previous_description' => get_user_meta( $user->ID, 'description', true ),
            'previous_url'         => $user->user_url,
            'previous_role'        => ! empty( $user->roles ) ? $user->roles[0] : 'subscriber',
        );
    }

    // ==================== SEARCH USERS ====================

    private function preview_search_users( $args ) {
        $search   = isset( $args['search'] ) ? sanitize_text_field( trim( (string) $args['search'] ) ) : '';
        $role     = isset( $args['role'] ) ? sanitize_text_field( trim( (string) $args['role'] ) ) : '';
        $per_page = isset( $args['per_page'] ) ? max( 1, min( 100, intval( $args['per_page'] ) ) ) : 10;
        $page     = isset( $args['page'] ) ? max( 1, intval( $args['page'] ) ) : 1;
        $orderby  = isset( $args['orderby'] ) ? (string) $args['orderby'] : 'name';
        $order    = isset( $args['order'] ) ? strtolower( (string) $args['order'] ) : 'asc';

        $valid_roles   = array( 'administrator', 'editor', 'author', 'contributor', 'subscriber' );
        $valid_orderby = array( 'id' => 'ID', 'name' => 'display_name', 'email' => 'email', 'registered' => 'registered' );

        if ( '' !== $role && ! in_array( $role, $valid_roles, true ) ) {
            return array( 'success' => false, 'error' => 'Invalid role filter: ' . $role . '. Allowed: ' . implode( ', ', $valid_roles ) . '.' );
        }

        if ( ! in_array( $order, array( 'asc', 'desc' ), true ) ) {
            $order = 'asc';
        }

        $wp_orderby = isset( $valid_orderby[ $orderby ] ) ? $valid_orderby[ $orderby ] : 'display_name';

        $query_args = array(
            'number'  => $per_page,
            'paged'   => $page,
            'orderby' => $wp_orderby,
            'order'   => strtoupper( $order ),
        );

        if ( '' !== $search ) {
            $query_args['search']         = '*' . $search . '*';
            $query_args['search_columns'] = array( 'user_login', 'user_email', 'display_name', 'user_nicename' );
        }

        if ( '' !== $role ) {
            $query_args['role'] = $role;
        }

        $user_query  = new WP_User_Query( $query_args );
        $users       = $user_query->get_results();
        $total_users = $user_query->get_total();

        $results = array();
        foreach ( $users as $user ) {
            $results[] = $this->format_user_data( $user, false );
        }

        $summary = 'Search users';
        if ( '' !== $search ) {
            $summary .= ' matching "' . $search . '"';
        }
        if ( '' !== $role ) {
            $summary .= ' with role ' . $role;
        }

        return array(
            'success' => true,
            'action'  => array(
                'type'             => 'search_users',
                'label'            => 'Search users',
                'summary'          => $summary . ' (page ' . $page . ', ' . $per_page . ' per page).',
                'rollback_plan'    => 'Read-only operation, no rollback needed.',
                'rollback_support' => 'none',
                'targets'          => array(),
                'args'             => array(
                    'search'   => $search,
                    'role'     => $role,
                    'per_page' => $per_page,
                    'page'     => $page,
                    'orderby'  => $orderby,
                    'order'    => $order,
                ),
            ),
        );
    }

    private function execute_search_users_action( $action ) {
        $args = isset( $action['args'] ) && is_array( $action['args'] ) ? $action['args'] : array();

        $search   = isset( $args['search'] ) ? sanitize_text_field( trim( (string) $args['search'] ) ) : '';
        $role     = isset( $args['role'] ) ? sanitize_text_field( trim( (string) $args['role'] ) ) : '';
        $per_page = isset( $args['per_page'] ) ? max( 1, min( 100, intval( $args['per_page'] ) ) ) : 10;
        $page     = isset( $args['page'] ) ? max( 1, intval( $args['page'] ) ) : 1;
        $orderby  = isset( $args['orderby'] ) ? (string) $args['orderby'] : 'name';
        $order    = isset( $args['order'] ) ? strtolower( (string) $args['order'] ) : 'asc';

        $valid_orderby = array( 'id' => 'ID', 'name' => 'display_name', 'email' => 'email', 'registered' => 'registered' );
        $wp_orderby    = isset( $valid_orderby[ $orderby ] ) ? $valid_orderby[ $orderby ] : 'display_name';

        $query_args = array(
            'number'  => $per_page,
            'paged'   => $page,
            'orderby' => $wp_orderby,
            'order'   => strtoupper( $order ),
        );

        if ( '' !== $search ) {
            $query_args['search']         = '*' . $search . '*';
            $query_args['search_columns'] = array( 'user_login', 'user_email', 'display_name', 'user_nicename' );
        }

        if ( '' !== $role ) {
            $query_args['role'] = $role;
        }

        $user_query  = new WP_User_Query( $query_args );
        $users       = $user_query->get_results();
        $total_users = $user_query->get_total();

        $results = array();
        foreach ( $users as $user ) {
            $results[] = $this->format_user_data( $user, false );
        }

        return array(
            'success'          => true,
            'summary'          => 'Found ' . $total_users . ' user(s). Showing page ' . $page . ' (' . count( $results ) . ' results).',
            'executed_actions' => array(
                array(
                    'type'        => 'search_users',
                    'total_found' => $total_users,
                    'page'        => $page,
                    'per_page'    => $per_page,
                    'users'       => $results,
                ),
            ),
            'rollback_entries' => array(),
        );
    }

    // ==================== GET USER ====================

    private function preview_get_user( $args ) {
        $user_id = isset( $args['user_id'] ) ? intval( $args['user_id'] ) : 0;

        if ( $user_id <= 0 ) {
            return array( 'success' => false, 'error' => 'user_id is required and must be a positive integer.' );
        }

        $user = get_user_by( 'id', $user_id );
        if ( ! $user ) {
            return array( 'success' => false, 'error' => 'User with ID ' . $user_id . ' not found.' );
        }

        return array(
            'success' => true,
            'action'  => array(
                'type'             => 'get_user',
                'label'            => 'Get user details',
                'summary'          => 'Retrieve full details for user "' . $user->display_name . '" (ID: ' . $user_id . ').',
                'rollback_plan'    => 'Read-only operation, no rollback needed.',
                'rollback_support' => 'none',
                'targets'          => array(
                    array(
                        'user_id'      => $user_id,
                        'display_name' => $user->display_name,
                    ),
                ),
                'args'             => array(
                    'user_id' => $user_id,
                ),
            ),
        );
    }

    private function execute_get_user_action( $action ) {
        $args    = isset( $action['args'] ) && is_array( $action['args'] ) ? $action['args'] : array();
        $user_id = isset( $args['user_id'] ) ? intval( $args['user_id'] ) : 0;

        $user = get_user_by( 'id', $user_id );
        if ( ! $user ) {
            return array( 'success' => false, 'error' => 'User with ID ' . $user_id . ' not found.' );
        }

        $user_data = $this->format_user_data( $user, true );

        return array(
            'success'          => true,
            'summary'          => 'Retrieved details for user "' . $user->display_name . '" (ID: ' . $user_id . ').',
            'executed_actions' => array(
                array(
                    'type' => 'get_user',
                    'user' => $user_data,
                ),
            ),
            'rollback_entries' => array(),
        );
    }

    // ==================== CREATE USER ====================

    private function preview_create_user( $args ) {
        $username     = isset( $args['username'] ) ? sanitize_user( trim( (string) $args['username'] ), true ) : '';
        $email        = isset( $args['email'] ) ? sanitize_email( trim( (string) $args['email'] ) ) : '';
        $role         = isset( $args['role'] ) ? sanitize_text_field( trim( (string) $args['role'] ) ) : 'subscriber';
        $first_name   = isset( $args['first_name'] ) ? sanitize_text_field( trim( (string) $args['first_name'] ) ) : '';
        $last_name    = isset( $args['last_name'] ) ? sanitize_text_field( trim( (string) $args['last_name'] ) ) : '';
        $display_name = isset( $args['display_name'] ) ? sanitize_text_field( trim( (string) $args['display_name'] ) ) : '';
        $description  = isset( $args['description'] ) ? sanitize_textarea_field( trim( (string) $args['description'] ) ) : '';
        $url          = isset( $args['url'] ) ? esc_url_raw( trim( (string) $args['url'] ) ) : '';
        $password     = isset( $args['password'] ) && '' !== trim( (string) $args['password'] ) ? (string) $args['password'] : '';

        if ( '' === $username ) {
            return array( 'success' => false, 'error' => 'Username is required to create a user.' );
        }

        if ( '' === $email || ! is_email( $email ) ) {
            return array( 'success' => false, 'error' => 'A valid email address is required to create a user.' );
        }

        if ( username_exists( $username ) ) {
            return array( 'success' => false, 'error' => 'Username "' . $username . '" already exists.' );
        }

        if ( email_exists( $email ) ) {
            return array( 'success' => false, 'error' => 'Email "' . $email . '" is already registered.' );
        }

        $valid_roles = array( 'administrator', 'editor', 'author', 'contributor', 'subscriber' );
        if ( ! in_array( $role, $valid_roles, true ) ) {
            return array( 'success' => false, 'error' => 'Invalid role: ' . $role . '. Allowed: ' . implode( ', ', $valid_roles ) . '.' );
        }

        $summary_parts   = array();
        $summary_parts[] = 'Create user "' . $username . '" (' . $email . ')';
        $summary_parts[] = 'Role: ' . $role;
        if ( '' !== $first_name || '' !== $last_name ) {
            $summary_parts[] = 'Name: ' . trim( $first_name . ' ' . $last_name );
        }
        if ( '' === $password ) {
            $summary_parts[] = 'Password: auto-generated';
        }

        return array(
            'success' => true,
            'action'  => array(
                'type'             => 'create_user',
                'label'            => 'Create user',
                'summary'          => implode( ' | ', $summary_parts ),
                'rollback_plan'    => 'Delete the newly created user.',
                'rollback_support' => 'full',
                'targets'          => array(
                    array(
                        'username' => $username,
                        'email'    => $email,
                        'role'     => $role,
                    ),
                ),
                'args'             => array(
                    'username'     => $username,
                    'email'        => $email,
                    'password'     => $password,
                    'role'         => $role,
                    'first_name'   => $first_name,
                    'last_name'    => $last_name,
                    'display_name' => $display_name,
                    'description'  => $description,
                    'url'          => $url,
                ),
            ),
        );
    }

    private function validate_create_user_action_args( $args ) {
        if ( empty( $args['username'] ) || '' === trim( (string) $args['username'] ) ) {
            return array( 'success' => false, 'error' => 'Username is required.' );
        }
        if ( empty( $args['email'] ) || ! is_email( (string) $args['email'] ) ) {
            return array( 'success' => false, 'error' => 'A valid email is required.' );
        }
        return array( 'success' => true );
    }

    private function execute_create_user_action( $action ) {
        $args = isset( $action['args'] ) && is_array( $action['args'] ) ? $action['args'] : array();

        $username = sanitize_user( trim( (string) $args['username'] ), true );
        $email    = sanitize_email( trim( (string) $args['email'] ) );
        $password = isset( $args['password'] ) && '' !== (string) $args['password'] ? (string) $args['password'] : wp_generate_password( 16, true, false );
        $role     = isset( $args['role'] ) ? (string) $args['role'] : 'subscriber';

        if ( username_exists( $username ) ) {
            return array( 'success' => false, 'error' => 'Username "' . $username . '" already exists.' );
        }

        if ( email_exists( $email ) ) {
            return array( 'success' => false, 'error' => 'Email "' . $email . '" is already registered.' );
        }

        $userdata = array(
            'user_login'   => $username,
            'user_email'   => $email,
            'user_pass'    => $password,
            'role'         => $role,
        );

        if ( ! empty( $args['first_name'] ) ) {
            $userdata['first_name'] = sanitize_text_field( (string) $args['first_name'] );
        }
        if ( ! empty( $args['last_name'] ) ) {
            $userdata['last_name'] = sanitize_text_field( (string) $args['last_name'] );
        }
        if ( ! empty( $args['display_name'] ) ) {
            $userdata['display_name'] = sanitize_text_field( (string) $args['display_name'] );
        }
        if ( ! empty( $args['description'] ) ) {
            $userdata['description'] = sanitize_textarea_field( (string) $args['description'] );
        }
        if ( ! empty( $args['url'] ) ) {
            $userdata['user_url'] = esc_url_raw( (string) $args['url'] );
        }

        $user_id = wp_insert_user( $userdata );
        if ( is_wp_error( $user_id ) ) {
            return array( 'success' => false, 'error' => 'Failed to create user: ' . $user_id->get_error_message() );
        }

        $user = get_user_by( 'id', $user_id );

        return array(
            'success'          => true,
            'summary'          => 'Created user "' . $username . '" (ID: ' . $user_id . ', role: ' . $role . ', email: ' . $email . ').',
            'executed_actions' => array(
                array(
                    'type'    => 'create_user',
                    'user_id' => $user_id,
                    'user'    => $user ? $this->format_user_data( $user, false ) : array( 'id' => $user_id ),
                ),
            ),
            'rollback_entries' => array(
                array(
                    'type'    => 'user_delete',
                    'user_id' => $user_id,
                ),
            ),
        );
    }

    // ==================== UPDATE USER ====================

    private function preview_update_user( $args ) {
        $user_id = isset( $args['user_id'] ) ? intval( $args['user_id'] ) : 0;

        if ( $user_id <= 0 ) {
            return array( 'success' => false, 'error' => 'user_id is required for updating a user.' );
        }

        $user = get_user_by( 'id', $user_id );
        if ( ! $user ) {
            return array( 'success' => false, 'error' => 'User with ID ' . $user_id . ' not found.' );
        }

        $rollback_snapshot = $this->build_user_restore_entry( $user );

        $changes = array();
        if ( isset( $args['email'] ) )        { $changes[] = 'email'; }
        if ( isset( $args['first_name'] ) )   { $changes[] = 'first_name'; }
        if ( isset( $args['last_name'] ) )    { $changes[] = 'last_name'; }
        if ( isset( $args['display_name'] ) ) { $changes[] = 'display_name'; }
        if ( isset( $args['nickname'] ) )     { $changes[] = 'nickname'; }
        if ( isset( $args['description'] ) )  { $changes[] = 'description'; }
        if ( isset( $args['url'] ) )          { $changes[] = 'url'; }
        if ( isset( $args['role'] ) )         { $changes[] = 'role -> ' . (string) $args['role']; }
        if ( isset( $args['password'] ) )     { $changes[] = 'password'; }

        if ( empty( $changes ) ) {
            return array( 'success' => false, 'error' => 'No fields specified to update.' );
        }

        if ( isset( $args['email'] ) && ! is_email( (string) $args['email'] ) ) {
            return array( 'success' => false, 'error' => 'Invalid email format: ' . (string) $args['email'] );
        }

        if ( isset( $args['email'] ) ) {
            $existing = email_exists( sanitize_email( (string) $args['email'] ) );
            if ( $existing && intval( $existing ) !== $user_id ) {
                return array( 'success' => false, 'error' => 'Email "' . (string) $args['email'] . '" is already in use by another user.' );
            }
        }

        if ( isset( $args['role'] ) ) {
            $valid_roles = array( 'administrator', 'editor', 'author', 'contributor', 'subscriber' );
            if ( ! in_array( (string) $args['role'], $valid_roles, true ) ) {
                return array( 'success' => false, 'error' => 'Invalid role: ' . (string) $args['role'] . '. Allowed: ' . implode( ', ', $valid_roles ) . '.' );
            }
        }

        $action_args = array(
            'user_id'           => $user_id,
            'rollback_snapshot' => $rollback_snapshot,
        );

        if ( isset( $args['email'] ) )        { $action_args['email']        = sanitize_email( (string) $args['email'] ); }
        if ( isset( $args['first_name'] ) )   { $action_args['first_name']   = sanitize_text_field( (string) $args['first_name'] ); }
        if ( isset( $args['last_name'] ) )    { $action_args['last_name']    = sanitize_text_field( (string) $args['last_name'] ); }
        if ( isset( $args['display_name'] ) ) { $action_args['display_name'] = sanitize_text_field( (string) $args['display_name'] ); }
        if ( isset( $args['nickname'] ) )     { $action_args['nickname']     = sanitize_text_field( (string) $args['nickname'] ); }
        if ( isset( $args['description'] ) )  { $action_args['description']  = sanitize_textarea_field( (string) $args['description'] ); }
        if ( isset( $args['url'] ) )          { $action_args['url']          = esc_url_raw( (string) $args['url'] ); }
        if ( isset( $args['role'] ) )         { $action_args['role']         = sanitize_text_field( (string) $args['role'] ); }
        if ( isset( $args['password'] ) )     { $action_args['password']     = (string) $args['password']; }

        return array(
            'success' => true,
            'action'  => array(
                'type'             => 'update_user',
                'label'            => 'Update user',
                'summary'          => 'Update user "' . $user->display_name . '" (ID: ' . $user_id . '). Changes: ' . implode( ', ', $changes ) . '.',
                'rollback_plan'    => 'Restore all previous user field values.',
                'rollback_support' => 'full',
                'targets'          => array(
                    array(
                        'user_id'      => $user_id,
                        'display_name' => $user->display_name,
                    ),
                ),
                'args'             => $action_args,
            ),
        );
    }

    private function validate_update_user_action_args( $args ) {
        if ( empty( $args['user_id'] ) || intval( $args['user_id'] ) <= 0 ) {
            return array( 'success' => false, 'error' => 'user_id is required for update.' );
        }
        if ( isset( $args['email'] ) && ! is_email( (string) $args['email'] ) ) {
            return array( 'success' => false, 'error' => 'Invalid email format.' );
        }
        if ( isset( $args['role'] ) ) {
            $valid_roles = array( 'administrator', 'editor', 'author', 'contributor', 'subscriber' );
            if ( ! in_array( (string) $args['role'], $valid_roles, true ) ) {
                return array( 'success' => false, 'error' => 'Invalid role: ' . (string) $args['role'] );
            }
        }
        return array( 'success' => true );
    }

    private function execute_update_user_action( $action ) {
        $args    = isset( $action['args'] ) && is_array( $action['args'] ) ? $action['args'] : array();
        $user_id = intval( $args['user_id'] );

        $user = get_user_by( 'id', $user_id );
        if ( ! $user ) {
            return array( 'success' => false, 'error' => 'User with ID ' . $user_id . ' not found.' );
        }

        $userdata = array( 'ID' => $user_id );

        if ( isset( $args['email'] ) )        { $userdata['user_email']   = sanitize_email( (string) $args['email'] ); }
        if ( isset( $args['first_name'] ) )   { $userdata['first_name']   = sanitize_text_field( (string) $args['first_name'] ); }
        if ( isset( $args['last_name'] ) )    { $userdata['last_name']    = sanitize_text_field( (string) $args['last_name'] ); }
        if ( isset( $args['display_name'] ) ) { $userdata['display_name'] = sanitize_text_field( (string) $args['display_name'] ); }
        if ( isset( $args['nickname'] ) )     { $userdata['nickname']     = sanitize_text_field( (string) $args['nickname'] ); }
        if ( isset( $args['description'] ) )  { $userdata['description']  = sanitize_textarea_field( (string) $args['description'] ); }
        if ( isset( $args['url'] ) )          { $userdata['user_url']     = esc_url_raw( (string) $args['url'] ); }
        if ( isset( $args['password'] ) )     { $userdata['user_pass']    = (string) $args['password']; }
        if ( isset( $args['role'] ) )         { $userdata['role']         = sanitize_text_field( (string) $args['role'] ); }

        $result = wp_update_user( $userdata );
        if ( is_wp_error( $result ) ) {
            return array( 'success' => false, 'error' => 'Failed to update user: ' . $result->get_error_message() );
        }

        $rollback_entries = array();
        if ( ! empty( $args['rollback_snapshot'] ) && is_array( $args['rollback_snapshot'] ) ) {
            $rollback_entries[] = $args['rollback_snapshot'];
        }

        return array(
            'success'          => true,
            'summary'          => 'Updated user "' . $user->display_name . '" (ID: ' . $user_id . ').',
            'executed_actions' => array(
                array(
                    'type'    => 'update_user',
                    'user_id' => $user_id,
                ),
            ),
            'rollback_entries' => $rollback_entries,
        );
    }

    // ==================== DELETE USER ====================

    private function preview_delete_user( $args ) {
        $user_id     = isset( $args['user_id'] ) ? intval( $args['user_id'] ) : 0;
        $reassign_to = isset( $args['reassign_to'] ) ? intval( $args['reassign_to'] ) : 0;

        if ( $user_id <= 0 ) {
            return array( 'success' => false, 'error' => 'user_id is required for deleting a user.' );
        }

        /* Safety: cannot delete user ID 1 (primary admin). */
        if ( 1 === $user_id ) {
            return array( 'success' => false, 'error' => 'Cannot delete user ID 1 (primary site administrator).' );
        }

        /* Safety: cannot delete the currently logged-in user. */
        $current_user_id = get_current_user_id();
        if ( $user_id === $current_user_id ) {
            return array( 'success' => false, 'error' => 'Cannot delete the currently logged-in user.' );
        }

        $user = get_user_by( 'id', $user_id );
        if ( ! $user ) {
            return array( 'success' => false, 'error' => 'User with ID ' . $user_id . ' not found.' );
        }

        /* Validate reassign target if provided. */
        if ( $reassign_to > 0 ) {
            if ( $reassign_to === $user_id ) {
                return array( 'success' => false, 'error' => 'Cannot reassign posts to the same user being deleted.' );
            }
            $reassign_user = get_user_by( 'id', $reassign_to );
            if ( ! $reassign_user ) {
                return array( 'success' => false, 'error' => 'Reassign target user (ID: ' . $reassign_to . ') not found.' );
            }
        }

        $post_count    = count_user_posts( $user_id );
        $summary_parts = array();
        $summary_parts[] = 'Delete user "' . $user->display_name . '" (ID: ' . $user_id . ', ' . $user->user_email . ')';
        $summary_parts[] = 'Role: ' . ( ! empty( $user->roles ) ? implode( ', ', $user->roles ) : 'none' );
        $summary_parts[] = 'Posts: ' . $post_count;
        if ( $reassign_to > 0 ) {
            $reassign_user = get_user_by( 'id', $reassign_to );
            $summary_parts[] = 'Reassign content to: "' . ( $reassign_user ? $reassign_user->display_name : 'ID ' . $reassign_to ) . '"';
        } else {
            $summary_parts[] = 'Content: will be deleted with user';
        }

        return array(
            'success' => true,
            'action'  => array(
                'type'             => 'delete_user',
                'label'            => 'Delete user',
                'summary'          => implode( ' | ', $summary_parts ),
                'rollback_plan'    => 'DESTRUCTIVE operation. User deletion cannot be rolled back. All user data will be permanently removed.',
                'rollback_support' => 'none',
                'targets'          => array(
                    array(
                        'user_id'      => $user_id,
                        'display_name' => $user->display_name,
                        'email'        => $user->user_email,
                        'post_count'   => $post_count,
                    ),
                ),
                'args'             => array(
                    'user_id'     => $user_id,
                    'reassign_to' => $reassign_to,
                ),
            ),
        );
    }

    private function validate_delete_user_action_args( $args ) {
        $user_id = isset( $args['user_id'] ) ? intval( $args['user_id'] ) : 0;

        if ( $user_id <= 0 ) {
            return array( 'success' => false, 'error' => 'user_id is required for delete.' );
        }
        if ( 1 === $user_id ) {
            return array( 'success' => false, 'error' => 'Cannot delete user ID 1.' );
        }
        if ( $user_id === get_current_user_id() ) {
            return array( 'success' => false, 'error' => 'Cannot delete the currently logged-in user.' );
        }

        return array( 'success' => true );
    }

    private function execute_delete_user_action( $action ) {
        $args        = isset( $action['args'] ) && is_array( $action['args'] ) ? $action['args'] : array();
        $user_id     = intval( $args['user_id'] );
        $reassign_to = isset( $args['reassign_to'] ) ? intval( $args['reassign_to'] ) : 0;

        $user = get_user_by( 'id', $user_id );
        if ( ! $user ) {
            return array( 'success' => false, 'error' => 'User with ID ' . $user_id . ' not found.' );
        }

        /* Safety checks again at execution time. */
        if ( 1 === $user_id ) {
            return array( 'success' => false, 'error' => 'Cannot delete user ID 1 (primary site administrator).' );
        }

        if ( $user_id === get_current_user_id() ) {
            return array( 'success' => false, 'error' => 'Cannot delete the currently logged-in user.' );
        }

        /* Require wp-admin/includes/user.php for wp_delete_user(). */
        if ( ! function_exists( 'wp_delete_user' ) ) {
            require_once ABSPATH . 'wp-admin/includes/user.php';
        }

        $display_name = $user->display_name;
        $email        = $user->user_email;

        $reassign_arg = $reassign_to > 0 ? $reassign_to : null;
        $deleted      = wp_delete_user( $user_id, $reassign_arg );

        if ( ! $deleted ) {
            return array( 'success' => false, 'error' => 'Failed to delete user (ID: ' . $user_id . ').' );
        }

        $summary = 'Deleted user "' . $display_name . '" (ID: ' . $user_id . ', email: ' . $email . ').';
        if ( $reassign_to > 0 ) {
            $summary .= ' Content reassigned to user ID ' . $reassign_to . '.';
        }

        return array(
            'success'          => true,
            'summary'          => $summary,
            'executed_actions' => array(
                array(
                    'type'        => 'delete_user',
                    'user_id'     => $user_id,
                    'reassign_to' => $reassign_to,
                ),
            ),
            'rollback_entries' => array(),
        );
    }

    // ==================== GET CURRENT USER ====================

    private function preview_get_current_user( $args ) {
        $current_user = wp_get_current_user();

        if ( ! $current_user || 0 === $current_user->ID ) {
            return array( 'success' => false, 'error' => 'No user is currently logged in.' );
        }

        return array(
            'success' => true,
            'action'  => array(
                'type'             => 'get_current_user',
                'label'            => 'Get current user details',
                'summary'          => 'Retrieve details for the currently logged-in user "' . $current_user->display_name . '" (ID: ' . $current_user->ID . ').',
                'rollback_plan'    => 'Read-only operation, no rollback needed.',
                'rollback_support' => 'none',
                'targets'          => array(
                    array(
                        'user_id'      => $current_user->ID,
                        'display_name' => $current_user->display_name,
                    ),
                ),
                'args'             => array(),
            ),
        );
    }

    private function execute_get_current_user_action( $action ) {
        $current_user = wp_get_current_user();

        if ( ! $current_user || 0 === $current_user->ID ) {
            return array( 'success' => false, 'error' => 'No user is currently logged in.' );
        }

        $user_data = $this->format_user_data( $current_user, true );

        return array(
            'success'          => true,
            'summary'          => 'Retrieved details for current user "' . $current_user->display_name . '" (ID: ' . $current_user->ID . ').',
            'executed_actions' => array(
                array(
                    'type' => 'get_current_user',
                    'user' => $user_data,
                ),
            ),
            'rollback_entries' => array(),
        );
    }

    // ==================== UPDATE CURRENT USER ====================

    private function preview_update_current_user( $args ) {
        $current_user = wp_get_current_user();

        if ( ! $current_user || 0 === $current_user->ID ) {
            return array( 'success' => false, 'error' => 'No user is currently logged in.' );
        }

        $user_id = $current_user->ID;

        $rollback_snapshot = $this->build_user_restore_entry( $current_user );

        $changes = array();
        if ( isset( $args['email'] ) )        { $changes[] = 'email'; }
        if ( isset( $args['first_name'] ) )   { $changes[] = 'first_name'; }
        if ( isset( $args['last_name'] ) )    { $changes[] = 'last_name'; }
        if ( isset( $args['display_name'] ) ) { $changes[] = 'display_name'; }
        if ( isset( $args['nickname'] ) )     { $changes[] = 'nickname'; }
        if ( isset( $args['description'] ) )  { $changes[] = 'description'; }
        if ( isset( $args['url'] ) )          { $changes[] = 'url'; }
        if ( isset( $args['role'] ) )         { $changes[] = 'role -> ' . (string) $args['role']; }
        if ( isset( $args['password'] ) )     { $changes[] = 'password'; }

        if ( empty( $changes ) ) {
            return array( 'success' => false, 'error' => 'No fields specified to update.' );
        }

        if ( isset( $args['email'] ) && ! is_email( (string) $args['email'] ) ) {
            return array( 'success' => false, 'error' => 'Invalid email format: ' . (string) $args['email'] );
        }

        if ( isset( $args['email'] ) ) {
            $existing = email_exists( sanitize_email( (string) $args['email'] ) );
            if ( $existing && intval( $existing ) !== $user_id ) {
                return array( 'success' => false, 'error' => 'Email "' . (string) $args['email'] . '" is already in use by another user.' );
            }
        }

        if ( isset( $args['role'] ) ) {
            $valid_roles = array( 'administrator', 'editor', 'author', 'contributor', 'subscriber' );
            if ( ! in_array( (string) $args['role'], $valid_roles, true ) ) {
                return array( 'success' => false, 'error' => 'Invalid role: ' . (string) $args['role'] . '. Allowed: ' . implode( ', ', $valid_roles ) . '.' );
            }
        }

        $action_args = array(
            'user_id'           => $user_id,
            'rollback_snapshot' => $rollback_snapshot,
        );

        if ( isset( $args['email'] ) )        { $action_args['email']        = sanitize_email( (string) $args['email'] ); }
        if ( isset( $args['first_name'] ) )   { $action_args['first_name']   = sanitize_text_field( (string) $args['first_name'] ); }
        if ( isset( $args['last_name'] ) )    { $action_args['last_name']    = sanitize_text_field( (string) $args['last_name'] ); }
        if ( isset( $args['display_name'] ) ) { $action_args['display_name'] = sanitize_text_field( (string) $args['display_name'] ); }
        if ( isset( $args['nickname'] ) )     { $action_args['nickname']     = sanitize_text_field( (string) $args['nickname'] ); }
        if ( isset( $args['description'] ) )  { $action_args['description']  = sanitize_textarea_field( (string) $args['description'] ); }
        if ( isset( $args['url'] ) )          { $action_args['url']          = esc_url_raw( (string) $args['url'] ); }
        if ( isset( $args['role'] ) )         { $action_args['role']         = sanitize_text_field( (string) $args['role'] ); }
        if ( isset( $args['password'] ) )     { $action_args['password']     = (string) $args['password']; }

        return array(
            'success' => true,
            'action'  => array(
                'type'             => 'update_current_user',
                'label'            => 'Update current user',
                'summary'          => 'Update current user "' . $current_user->display_name . '" (ID: ' . $user_id . '). Changes: ' . implode( ', ', $changes ) . '.',
                'rollback_plan'    => 'Restore all previous user field values.',
                'rollback_support' => 'full',
                'targets'          => array(
                    array(
                        'user_id'      => $user_id,
                        'display_name' => $current_user->display_name,
                    ),
                ),
                'args'             => $action_args,
            ),
        );
    }

    private function validate_update_current_user_action_args( $args ) {
        if ( isset( $args['email'] ) && ! is_email( (string) $args['email'] ) ) {
            return array( 'success' => false, 'error' => 'Invalid email format.' );
        }
        if ( isset( $args['role'] ) ) {
            $valid_roles = array( 'administrator', 'editor', 'author', 'contributor', 'subscriber' );
            if ( ! in_array( (string) $args['role'], $valid_roles, true ) ) {
                return array( 'success' => false, 'error' => 'Invalid role: ' . (string) $args['role'] );
            }
        }
        return array( 'success' => true );
    }

    private function execute_update_current_user_action( $action ) {
        $args = isset( $action['args'] ) && is_array( $action['args'] ) ? $action['args'] : array();

        $current_user = wp_get_current_user();
        if ( ! $current_user || 0 === $current_user->ID ) {
            return array( 'success' => false, 'error' => 'No user is currently logged in.' );
        }

        $user_id = $current_user->ID;

        $userdata = array( 'ID' => $user_id );

        if ( isset( $args['email'] ) )        { $userdata['user_email']   = sanitize_email( (string) $args['email'] ); }
        if ( isset( $args['first_name'] ) )   { $userdata['first_name']   = sanitize_text_field( (string) $args['first_name'] ); }
        if ( isset( $args['last_name'] ) )    { $userdata['last_name']    = sanitize_text_field( (string) $args['last_name'] ); }
        if ( isset( $args['display_name'] ) ) { $userdata['display_name'] = sanitize_text_field( (string) $args['display_name'] ); }
        if ( isset( $args['nickname'] ) )     { $userdata['nickname']     = sanitize_text_field( (string) $args['nickname'] ); }
        if ( isset( $args['description'] ) )  { $userdata['description']  = sanitize_textarea_field( (string) $args['description'] ); }
        if ( isset( $args['url'] ) )          { $userdata['user_url']     = esc_url_raw( (string) $args['url'] ); }
        if ( isset( $args['password'] ) )     { $userdata['user_pass']    = (string) $args['password']; }
        if ( isset( $args['role'] ) )         { $userdata['role']         = sanitize_text_field( (string) $args['role'] ); }

        $result = wp_update_user( $userdata );
        if ( is_wp_error( $result ) ) {
            return array( 'success' => false, 'error' => 'Failed to update current user: ' . $result->get_error_message() );
        }

        $rollback_entries = array();
        if ( ! empty( $args['rollback_snapshot'] ) && is_array( $args['rollback_snapshot'] ) ) {
            $rollback_entries[] = $args['rollback_snapshot'];
        }

        return array(
            'success'          => true,
            'summary'          => 'Updated current user "' . $current_user->display_name . '" (ID: ' . $user_id . ').',
            'executed_actions' => array(
                array(
                    'type'    => 'update_current_user',
                    'user_id' => $user_id,
                ),
            ),
            'rollback_entries' => $rollback_entries,
        );
    }
}
