<?php
/**
 * UM User List AJAX Handlers
 * * This file contains all AJAX handlers and helper functions specifically for the UM User List widget.
 * Separated from the main elementor-um-essential.php file for better organization.
 */

if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly
}

/**
 * Resolve widget visibility rules from saved Elementor document data.
 */
function um_ajax_get_visibility_map_from_elementor( int $post_id, string $widget_id ): array {
	if ( $post_id < 1 || $widget_id === '' ) {
		return [];
	}
	$raw = get_post_meta( $post_id, '_elementor_data', true );
	if ( ! is_string( $raw ) || $raw === '' ) {
		return [];
	}
	$data = json_decode( $raw, true );
	if ( ! is_array( $data ) ) {
		return [];
	}
	return um_ajax_find_widget_visibility_map( $data, $widget_id );
}

/**
 * Walk Elementor element tree and return visibility map for a widget id.
 */
function um_ajax_find_widget_visibility_map( array $elements, string $widget_id ): array {
	foreach ( $elements as $element ) {
		if ( ! is_array( $element ) ) {
			continue;
		}
		if ( isset( $element['id'] ) && $element['id'] === $widget_id ) {
			$repeater = $element['settings']['um_user_meta_control'] ?? [];
			return class_exists( 'UM_Elementor_Field_Visibility' )
				? UM_Elementor_Field_Visibility::build_visibility_map( $repeater )
				: [];
		}
		if ( ! empty( $element['elements'] ) && is_array( $element['elements'] ) ) {
			$found = um_ajax_find_widget_visibility_map( $element['elements'], $widget_id );
			if ( ! empty( $found ) ) {
				return $found;
			}
		}
	}
	return [];
}

// Removed get_widget_settings_from_id because settings are passed via JSON payload

/**
 * AJAX handler for Ultimate Member user list widget
 * * Handles filtering, searching, and pagination for the UM User List widget
 */
function um_ajax_filter_users() {
    // Verify nonce first, before any file I/O or class checks.
    $nonce = $_POST['nonce'] ?? '';
    if (!wp_verify_nonce($nonce, 'um_filter_nonce')) {
        wp_send_json_error(['message' => 'Security check failed']);
        return;
    }

    // Always load the autoloader for AJAX requests
    $autoloader_path = UM_USER_ELEMENTOR_PATH . 'modules/autoload.php';
    
    if (file_exists($autoloader_path)) {
        require_once $autoloader_path;
    } else {
        wp_send_json_error(['message' => 'Autoloader file not found at: ' . $autoloader_path]);
        return;
    }
    
    // Check if class exists after loading autoloader
    $class_name = 'UM_Elementor\\Helpers\\UM_Elementor_Utils';
    
    if (!class_exists($class_name)) {
        // Try to load the class file directly
        $class_file = UM_USER_ELEMENTOR_PATH . 'modules/helpers/UM_Elementor_Utils.php';
        
        if (file_exists($class_file)) {
            require_once $class_file;
        }
        
        if (!class_exists($class_name)) {
            $debug_info = (defined('WP_DEBUG') && WP_DEBUG) ? [
                'autoloader_path' => $autoloader_path,
                'class_file_exists' => file_exists($class_file),
            ] : [];

            wp_send_json_error([
                'message' => 'Plugin initialisation error.',
                'debug_info' => $debug_info,
            ]);
            return;
        }
    }
    
    // *** START SECURITY CHECK ***
    // Check if the current user is privileged.
    $is_privileged_user = current_user_can('list_users');
    // *** END SECURITY CHECK ***


    $page = max( 1, intval( $_POST['page'] ?? 1 ) );
    $per_page = max(1, min(100, intval($_POST['per_page'] ?? 12)));
    $search = sanitize_text_field($_POST['search'] ?? '');
    $filters = isset( $_POST['filters'] ) && is_array( $_POST['filters'] ) ? wp_unslash( $_POST['filters'] ) : [];

    $widget_id      = sanitize_text_field( wp_unslash( $_POST['widget_id'] ?? '' ) );
    $post_id        = absint( wp_unslash( $_POST['post_id'] ?? 0 ) );
    $visibility_map = um_ajax_get_visibility_map_from_elementor( $post_id, $widget_id );

    $widget_settings = class_exists( 'UM_Elementor_Ajax_Widget_Settings', false )
        ? UM_Elementor_Ajax_Widget_Settings::from_post_um_list()
        : [];

    $allowed_meta = array_values(
        array_unique(
            array_filter(
                array_map( 'sanitize_key', (array) ( $widget_settings['um_elementor_user_meta_fields'] ?? [] ) )
            )
        )
    );
    
    // Use UM_User_Query_Engine format settings array instead of complex WP_Query arguments
    $settings = array_merge(
        $widget_settings,
        [
            'users_per_page' => $per_page,
            'paged' => $page,
            'search' => $search,
        ]
    );

    // Add filters — only keys exposed by the widget configuration
    if ( ! empty( $filters ) && ! empty( $allowed_meta ) ) {
        $meta_query = [];
        
        foreach ($filters as $filter_key => $filter_values) {
            if (!empty($filter_values)) {
                // Sanitize the filter key
                $filter_key = sanitize_key($filter_key);

                if ( $filter_key === '' || ! in_array( $filter_key, $allowed_meta, true ) ) {
                    continue;
                }
                
                if (is_array($filter_values)) {
                    // Multiple values (checkbox) - sanitize each value
                    $sanitized_values = array_map('sanitize_text_field', $filter_values);
                    
                    // Create OR conditions for serialized data
                    $or_conditions = [];
                    
                    // Add exact match for non-serialized data
                    $or_conditions[] = [
                        'key' => $filter_key,
                        'value' => $sanitized_values,
                        'compare' => 'IN'
                    ];
                    
                    // Add LIKE conditions for serialized data
                    foreach ($sanitized_values as $value) {
                        $or_conditions[] = [
                            'key' => $filter_key,
                            'value' => '"' . $value . '"',
                            'compare' => 'LIKE'
                        ];
                    }
                    
                    // Add the OR group to meta_query
                    $meta_query[] = array_merge(['relation' => 'OR'], $or_conditions);
                    
                } else {
                    // Single value (dropdown/radio) - sanitize the value
                    $filter_value = sanitize_text_field($filter_values);
                    
                    // Create OR conditions for serialized data
                    $or_conditions = [];
                    
                    // Add exact match for non-serialized data
                    $or_conditions[] = [
                        'key' => $filter_key,
                        'value' => $filter_value,
                        'compare' => '='
                    ];
                    
                    // Add LIKE condition for serialized data
                    $or_conditions[] = [
                        'key' => $filter_key,
                        'value' => '"' . $filter_value . '"',
                        'compare' => 'LIKE'
                    ];
                    
                    // Add the OR group to meta_query
                    $meta_query[] = array_merge(['relation' => 'OR'], $or_conditions);
                }
            }
        }
        
        if (!empty($meta_query)) {
            $settings['meta_query'] = $meta_query;
        }
    }

    // Get users using the query engine
    try {
        if (um_use_new_query_engine()) {
            if (!empty($settings['search'])) {
                $settings['search_columns'] = $is_privileged_user
                    ? ['user_login', 'user_nicename', 'user_email', 'display_name']
                    : ['display_name'];
            }
            $result = \UM_User_Query_Engine::get_users($settings);
            $users = $result['users'];
            $total_users = $result['total'];
        } else {
            $args = \UM_Elementor\Helpers\UM_User_Query_Legacy::build($settings);
            $args['paged'] = $settings['paged'] ?? 1;
            
            if (!empty($settings['meta_query'])) {
                if (isset($args['meta_query'])) {
                    $args['meta_query'] = array_merge(['relation' => 'AND'], [$args['meta_query'], $settings['meta_query']]);
                } else {
                    $args['meta_query'] = $settings['meta_query'];
                }
            }
            
            if (!empty($settings['search'])) {
                $args['search'] = '*' . $settings['search'] . '*';
            }
            
            $members_query = new \WP_User_Query($args);
            $users_raw = $members_query->get_results();
            $total_users = \UM_Elementor\Helpers\UM_User_Query_Legacy::getTotalUsers($args);
            $users = \UM_Elementor\Helpers\UM_User_Query_Legacy::filterDisplayableUsers($users_raw);
        }

        $requested_meta_fields = $widget_settings['um_elementor_user_meta_fields'] ?? [];
        $users_array = \WP_User_List_Ajax::build_users_response_array($users, $is_privileged_user, $requested_meta_fields, true, $visibility_map);
        
    } catch (Exception $e) {
        $debug_info = (defined('WP_DEBUG') && WP_DEBUG) ? [
            'exception_message' => $e->getMessage(),
            'exception_file' => $e->getFile(),
            'exception_line' => $e->getLine(),
            'exception_trace' => $e->getTraceAsString(),
        ] : [];

        wp_send_json_error([
            'message' => __('Error fetching users.', 'ultimate-member-widgets-for-elementor'),
            'debug_info' => $debug_info,
        ]);
        return;
    }
    
    // Calculate pagination
    $total_pages = ceil($total_users / $per_page);
    
    // If requested page is beyond total pages, adjust to last page
    if ($page > $total_pages && $total_pages > 0) {
        $page = $total_pages;
        
        // Re-run the query with the corrected page
        $settings['paged'] = $page;
        
        if (um_use_new_query_engine()) {
            $result = \UM_User_Query_Engine::get_users($settings);
            $users = $result['users'];
        } else {
            $args = \UM_Elementor\Helpers\UM_User_Query_Legacy::build($settings);
            $args['paged'] = $page;
            
            if (!empty($settings['meta_query'])) {
                if (isset($args['meta_query'])) {
                    $args['meta_query'] = array_merge(['relation' => 'AND'], [$args['meta_query'], $settings['meta_query']]);
                } else {
                    $args['meta_query'] = $settings['meta_query'];
                }
            }
            
            if (!empty($settings['search'])) {
                $args['search'] = '*' . $settings['search'] . '*';
            }
            
            $members_query = new \WP_User_Query($args);
            $users_raw = $members_query->get_results();
            $users = \UM_Elementor\Helpers\UM_User_Query_Legacy::filterDisplayableUsers($users_raw);
        }

        $requested_meta_fields = $widget_settings['um_elementor_user_meta_fields'] ?? [];
        $users_array = \WP_User_List_Ajax::build_users_response_array($users, $is_privileged_user, $requested_meta_fields, true, $visibility_map);
    }
    
    $response = [
        'users' => $users_array,
        'total_users' => $total_users,
        'current_page' => $page,
        'total_pages' => $total_pages,
        'per_page' => $per_page,
        'widget_settings' => $widget_settings,
    ];

    wp_send_json_success($response);
}

// Hook the AJAX handlers
add_action('wp_ajax_um_filter_users', 'um_ajax_filter_users');
add_action('wp_ajax_nopriv_um_filter_users', 'um_ajax_filter_users');
