<?php

namespace ACB\Inc;
use \ACB\Inc\Ajax_Parts\ACB_MessageCreation;

defined('ABSPATH') or die('Hey, what are you doing here? You silly human!');
/**
 * All Ajax call here
 */
class ACB_AjaxHandler {

    public function __construct() {
        $this->events();
    }

    public function events() {
        
        add_action( 'wp_ajax_acb_data_truncate', array( $this, 'ACB_message_truncate' ) ); 
        add_action("wp_ajax_nopriv_acb_data_truncate", array( $this, 'ACB_message_truncate'));
        
        /* Demo check Creation */
        add_action( 'wp_ajax_show_user_inputed_data', array( $this, 'ACB_message_creation' ) ); 
        add_action("wp_ajax_nopriv_show_user_inputed_data", array( $this, 'ACB_message_creation'));
        
        /* Firebase Configuration */
        add_action( 'wp_ajax_acb_save_firebase_config', array( $this, 'save_firebase_config' ) );
        add_action( 'wp_ajax_acb_test_firebase_connection', array( $this, 'test_firebase_connection' ) );
        add_action( 'wp_ajax_acb_firebase_auth', array( $this, 'firebase_auth' ) );
        
        /* User Management */
        add_action( 'wp_ajax_acb_get_all_users', array( $this, 'get_all_users' ) );
        add_action( 'wp_ajax_acb_get_users', array( $this, 'get_users_with_admin_status' ) );
        add_action( 'wp_ajax_nopriv_acb_get_users', array( $this, 'get_users_with_admin_status' ) );
        add_action( 'wp_ajax_acb_toggle_user_agent', array( $this, 'toggle_user_agent' ) );
        add_action( 'wp_ajax_acb_sync_firebase_users', array( $this, 'sync_firebase_users' ) );
        add_action( 'wp_ajax_acb_get_support_settings', array( $this, 'get_support_settings' ) );
        add_action( 'wp_ajax_nopriv_acb_get_support_settings', array( $this, 'get_support_settings' ) );
        add_action( 'wp_ajax_acb_get_widget_settings', array( $this, 'get_widget_settings' ) );
        add_action( 'wp_ajax_nopriv_acb_get_widget_settings', array( $this, 'get_widget_settings' ) );
        add_action( 'wp_ajax_acb_save_widget_settings', array( $this, 'save_widget_settings' ) );
        add_action( 'wp_ajax_acb_save_support_settings', array( $this, 'save_support_settings' ) );
        add_action( 'wp_ajax_acb_check_user_admin_status', array( $this, 'check_user_admin_status' ) );
        add_action( 'wp_ajax_nopriv_acb_check_user_admin_status', array( $this, 'check_user_admin_status' ) );
        
    }
    
    /**Chat data truncate */
    public function ACB_message_truncate() {
        // Verify nonce for security
         if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'acb_nonce' ) ) {
			wp_send_json_error([
				'message' => __( 'Security check failed.', 'acb' ),
			]);
		}
        
        $ACB_message_truncate = new ACB_MessageCreation();
        $ACB_message_truncate->ACB_message_truncate(); 
    }

    /**Chat data fetch */
    public function ACB_message_creation() {
        // Verify nonce for security
         if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'acb_nonce' ) ) {
			wp_send_json_error([
				'message' => __( 'Security check failed.', 'acb' ),
			]);
		}
        
        $ACB_message_creation = new ACB_MessageCreation();
        $ACB_message_creation->ACB_message_creation();  
    }

    /**
     * Save Firebase configuration - Only for administrators
     */
    public function save_firebase_config() {
        // Verify nonce
         if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'acb_nonce' ) ) {
			wp_send_json_error([
				'message' => __( 'Security check failed.', 'acb' ),
			]);
		}

        // Check user permissions - Only administrators can save Firebase config
        if (!current_user_can('manage_options')) {
            wp_send_json_error('Insufficient permissions - Only administrators can save Firebase configuration');
        }

        // Validate POST data exists
        if (!isset($_POST['config']) || empty($_POST['config'])) {
            wp_send_json_error('Configuration data is required');
        }

        // Sanitize and unslash the config data
        $config = wp_unslash($_POST['config']);
        $config = sanitize_textarea_field($config);
        
        
        $config_array = json_decode($config, true);
        
        // Check for JSON decode errors
        if (json_last_error() !== JSON_ERROR_NONE) {
            $error_msg = 'Invalid configuration format: ' . json_last_error_msg();
           
            wp_send_json_error($error_msg);
        }

        if (!is_array($config_array)) {
            wp_send_json_error('Configuration must be a valid JSON object');
        }

        // Validate required fields
        $required_fields = ['apiKey', 'authDomain', 'projectId', 'storageBucket', 'messagingSenderId', 'appId'];
        foreach ($required_fields as $field) {
            if (!isset($config_array[$field]) || empty(trim($config_array[$field]))) {
                $error_msg = "Missing or empty required field: $field";
                wp_send_json_error($error_msg);
            }
        }

        // Sanitize individual fields
        $sanitized_config = array();
        foreach ($config_array as $key => $value) {
            $sanitized_config[$key] = sanitize_text_field( wp_unslash($value)); 
        }
        
        // Validate sanitized config still has required fields
        foreach ($required_fields as $field) {
            if (!isset($sanitized_config[$field]) || empty($sanitized_config[$field])) {
                wp_send_json_error("Invalid data for required field: $field");
            }
        }
        
        // Check if the option already exists and has the same value
        $existing_config = get_option('firebaseConfig', []);
        
        // Save to WordPress options
        $saved = update_option('firebaseConfig', $sanitized_config);
       
        // Verify the option was actually saved
        $saved_config = get_option('firebaseConfig', []);
        
        if ($saved || $saved_config == $sanitized_config) {
            wp_send_json_success('Firebase configuration saved successfully');
        } else {
            wp_send_json_error('Failed to save configuration - WordPress option update failed');
        }
    }

    /**
     * Test Firebase connection - Only for administrators
     */
    public function test_firebase_connection() {
        // Verify nonce
         if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'acb_nonce' ) ) {
			wp_send_json_error([
				'message' => __( 'Security check failed.', 'acb' ),
			]);
		}

        // Check user permissions - Only administrators can test Firebase connection
        if (!current_user_can('manage_options')) {
            wp_send_json_error('Insufficient permissions - Only administrators can test Firebase connection');
        }

        // Validate POST data exists
        if (!isset($_POST['config']) || empty($_POST['config'])) {
            wp_send_json_error('Configuration data is required');
        }

        // Sanitize and unslash the config data
        $config = wp_unslash($_POST['config']);
        $config = sanitize_textarea_field($config);
        $config_array = json_decode($config, true);

        // Check for JSON decode errors
        if (json_last_error() !== JSON_ERROR_NONE) {
            wp_send_json_error('Invalid configuration format: ' . json_last_error_msg());
        }

        if (!is_array($config_array)) {
            wp_send_json_error('Configuration must be a valid JSON object');
        }

        // Validate required fields exist
        if (!isset($config_array['apiKey']) || !isset($config_array['projectId'])) {
            wp_send_json_error('Missing required configuration fields (apiKey, projectId)');
        }

        try {
            // Sanitize the API key and project ID
            $api_key = sanitize_text_field($config_array['apiKey']);
            $project_id = sanitize_text_field($config_array['projectId']);
            
            if (empty($api_key) || empty($project_id)) {
                wp_send_json_error('Invalid API key or project ID');
            }
            
            // Test Firebase Auth API
            $test_url = "https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=" . urlencode($api_key);
            $response = wp_remote_post($test_url, [
                'body' => wp_json_encode([
                    'email' => 'test@example.com',
                    'password' => 'testpassword123',
                    'returnSecureToken' => true
                ]),
                'headers' => [
                    'Content-Type' => 'application/json'
                ],
                'timeout' => 10,
                'sslverify' => true
            ]);

            if (is_wp_error($response)) {
                wp_send_json_error('Connection failed: ' . esc_html($response->get_error_message()));
            }

            $response_code = wp_remote_retrieve_response_code($response);
            $body = wp_remote_retrieve_body($response);
            $data = json_decode($body, true);

            // Check if we got a valid response
            if ($response_code >= 200 && $response_code < 500) {
                wp_send_json_success('Firebase connection successful! Configuration is valid.');
            } else {
                wp_send_json_error('Firebase connection failed. Response code: ' . absint($response_code));
            }

        } catch (Exception $e) {
            wp_send_json_error('Connection test failed: ' . esc_html($e->getMessage()));
        }
    }

    /**
     * Handle Firebase user authentication - Available to all logged-in users
     */
    public function firebase_auth() {
        // Verify nonce
         if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'acb_nonce' ) ) {
			wp_send_json_error([
				'message' => __( 'Security check failed.', 'acb' ),
			]);
		}

        // Check user permissions - Any logged-in user can authenticate
        if (!is_user_logged_in()) {
            wp_send_json_error('User must be logged in');
        }

        // Validate required POST data
        $required_fields = ['firebase_uid', 'user_email'];
        foreach ($required_fields as $field) {
            if (!isset($_POST[$field]) || empty(trim($_POST[$field]))) {
                wp_send_json_error("Missing required field: $field");
            }
        }

        // Sanitize input data
        $firebase_uid = sanitize_text_field(wp_unslash($_POST['firebase_uid']));
        $user_name = isset($_POST['user_name']) ? sanitize_text_field(wp_unslash($_POST['user_name'])) : '';
        $user_email = sanitize_email(wp_unslash($_POST['user_email']));
        $user_avatar = isset($_POST['user_avatar']) ? esc_url_raw(wp_unslash($_POST['user_avatar'])) : '';
        $auth_provider = isset($_POST['auth_provider']) ? sanitize_text_field(wp_unslash($_POST['auth_provider'])) : 'firebase';

        // Validate email format
        if (!is_email($user_email)) {
            wp_send_json_error('Invalid email format');
        }

        // Validate firebase_uid is not empty after sanitization
        if (empty($firebase_uid)) {
            wp_send_json_error('Invalid Firebase UID');
        }

        try {
            // Check if user exists in WordPress
            $wp_user = get_user_by('email', $user_email);
            
            if (!$wp_user) {
                // Create new WordPress user
                $username = !empty($user_name) ? sanitize_user($user_name) : sanitize_user($user_email);
                $counter = 1;
                $original_username = $username;
                
                // Ensure unique username
                while (username_exists($username)) {
                    $username = $original_username . '_' . $counter;
                    $counter++;
                }
                
                // Generate secure password
                $password = wp_generate_password(12, false);
                $user_id = wp_create_user($username, $password, $user_email);
                
                if (is_wp_error($user_id)) {
                    wp_send_json_error('Failed to create WordPress user: ' . esc_html($user_id->get_error_message()));
                }
                
                // Set display name
                $display_name = !empty($user_name) ? $user_name : $username;
                wp_update_user([
                    'ID' => $user_id,
                    'display_name' => $display_name,
                    'first_name' => $display_name
                ]);
                
                // Add user meta
                update_user_meta($user_id, 'firebase_uid', $firebase_uid);
                if (!empty($user_avatar)) {
                    update_user_meta($user_id, 'firebase_avatar', $user_avatar);
                }
                update_user_meta($user_id, 'auth_provider', $auth_provider);
                
            } else {
                // Update existing user
                $user_id = $wp_user->ID;
                update_user_meta($user_id, 'firebase_uid', $firebase_uid);
                
                if (!empty($user_avatar)) {
                    update_user_meta($user_id, 'firebase_avatar', $user_avatar);
                }
                update_user_meta($user_id, 'auth_provider', $auth_provider);
                
                // Update display name if provided and different
                if (!empty($user_name) && $wp_user->display_name !== $user_name) {
                    wp_update_user([
                        'ID' => $user_id,
                        'display_name' => $user_name
                    ]);
                }
            }
            
            // Add user to chat users table
            $this->add_user_to_chat_table($firebase_uid, $user_name, $user_email, $user_avatar, $auth_provider);
            
            // Log in the user
            wp_set_current_user($user_id);
            wp_set_auth_cookie($user_id);
            
            wp_send_json_success([
                'user_id' => absint($user_id),
                'message' => 'Authentication successful'
            ]);
            
        } catch (Exception $e) {
            wp_send_json_error('Authentication failed: ' . esc_html($e->getMessage()));
        }
    }

    /**
     * Get all chat users - Only for administrators
     */
    public function get_all_users() {
        // Verify nonce
         if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'acb_nonce' ) ) {
			wp_send_json_error([
				'message' => __( 'Security check failed.', 'acb' ),
			]);
		}

        // Check user permissions - Only administrators can view all users
        if (!current_user_can('manage_options')) {
            wp_send_json_error('Insufficient permissions - Only administrators can view users');
        }

        global $wpdb;
        $table_users = $wpdb->prefix . 'acb_users';
        
        // Validate table exists
        if ($wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $table_users)) !== $table_users) {
            wp_send_json_error('Users table does not exist');
        }

        // Get all users
        $users = $wpdb->get_results(
            "SELECT * FROM $table_users ORDER BY created_at DESC"
        );

        if ($users === false) {
            wp_send_json_error('Failed to retrieve users');
        }

        $formatted_users = [];
        foreach ($users as $user) {
            // Check if user is online (last seen within 2 minutes)
            $last_seen_time = strtotime($user->last_seen);
            $is_online = (time() - $last_seen_time) < 120; // 2 minutes
            
            $formatted_users[] = [
                'id' => absint($user->id),
                'firebase_uid' => esc_html($user->firebase_uid),
                'user_name' => esc_html($user->user_name),
                'user_email' => esc_html($user->user_email),
                'user_avatar' => esc_url($user->user_avatar),
                'auth_provider' => esc_html($user->auth_provider),
                'is_admin' => (bool) $user->is_admin,
                'is_online' => $is_online,
                'last_seen' => esc_html($user->last_seen),
                'created_at' => esc_html($user->created_at),
                'formatted_last_seen' => esc_html(date('M d, Y > h:i A', strtotime($user->last_seen)))
            ];
        }

        wp_send_json_success([
            'users' => $formatted_users,
            'total' => count($formatted_users)
        ]);
    }

    /**
     * Toggle user admin status - Only for administrators
     */
    public function toggle_user_agent() {

        if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'acb_nonce' ) ) {
			wp_send_json_error([
				'message' => __( 'Security check failed.', 'acb' ),
			]);
		}

        // Check user permissions - Only administrators can change user roles
        if (!current_user_can('manage_options')) {
            wp_send_json_error('Insufficient permissions - Only administrators can change user roles');
        }

        // Validate required fields
        if (!isset($_POST['user_id']) || !isset($_POST['new_role'])) {
            wp_send_json_error('Missing required fields');
        }

        $user_id = absint($_POST['user_id']);
        $new_role = sanitize_text_field(wp_unslash($_POST['new_role']));

        // Validate inputs
        if ($user_id <= 0) {
            wp_send_json_error('Invalid user ID');
        }

        if (!in_array($new_role, ['admin', 'regular'], true)) {
            wp_send_json_error('Invalid role specified');
        }

        global $wpdb;
        $table_users = $wpdb->prefix . 'acb_users';
        
        // Validate table exists
        if ($wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $table_users)) !== $table_users) {
            wp_send_json_error('Users table does not exist');
        }

        // Check if user exists
        $user = $wpdb->get_row(
            $wpdb->prepare("SELECT * FROM $table_users WHERE id = %d", $user_id)
        );

        if (!$user) {
            wp_send_json_error('User not found');
        }

        // Update user role
        $is_admin = ($new_role === 'admin') ? 1 : 0;
        $result = $wpdb->update(
            $table_users,
            [
                'is_admin' => $is_admin,
                'updated_at' => current_time('mysql')
            ],
            ['id' => $user_id],
            ['%d', '%s'],
            ['%d']
        );

        if ($result === false) {
            wp_send_json_error('Failed to update user role');
        }

        wp_send_json_success([
            'message' => 'User role updated successfully',
            'user_id' => $user_id,
            'new_role' => $new_role
        ]);
    }

    /**
     * Get support system settings - Available to all users (read-only)
     */
    public function get_support_settings() {
        // Verify nonce - Use firebase nonce since it's available to all users
         if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'acb_nonce' ) ) {
			wp_send_json_error([
				'message' => __( 'Security check failed.', 'acb' ),
			]);
		}
        // No permission check needed - all users need to know if support mode is enabled
        $support_system_enabled = get_option('acb_support_system_enabled', false);
        
        // Fix: Ensure proper boolean conversion
        $support_system_enabled = ($support_system_enabled === '1' || $support_system_enabled === 1 || $support_system_enabled === true || $support_system_enabled === 'true');

        wp_send_json_success([
            'support_system_enabled' => $support_system_enabled
        ]);
    }

    /**
     * Save support system settings - Only for administrators
     */
    public function save_support_settings() {
        // Verify nonce
         if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'acb_nonce' ) ) {
			wp_send_json_error([
				'message' => __( 'Security check failed.', 'acb' ),
			]);
		}

        // Check user permissions - Only administrators can save settings
        if (!current_user_can('manage_options')) {
            wp_send_json_error('Insufficient permissions - Only administrators can save settings');
        }

        // Get and validate the setting - Fix: Proper boolean conversion
        $support_system_enabled = isset($_POST['support_system_enabled']) && 
            ($_POST['support_system_enabled'] === 'true' || $_POST['support_system_enabled'] === true || $_POST['support_system_enabled'] === '1' || $_POST['support_system_enabled'] === 1);

        // Save the setting
        $result = update_option('acb_support_system_enabled', $support_system_enabled);

        if ($result || get_option('acb_support_system_enabled') == $support_system_enabled) {
            wp_send_json_success([
                'message' => 'Support system settings saved successfully',
                'support_system_enabled' => $support_system_enabled
            ]);
        } else {
            wp_send_json_error('Failed to save support system settings');
        }
    }

    /**
     * Get users with admin status - Available to all authenticated users (for React components)
     */
    public function get_users_with_admin_status() {
        // Verify nonce
        if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'acb_nonce' ) ) {
			wp_send_json_error([
				'message' => __( 'Security check failed.', 'acb' ),
			]);
		}
        global $wpdb;
        $table_users = $wpdb->prefix . 'acb_users';
        
        // Validate table exists
        if ($wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $table_users)) !== $table_users) {
            wp_send_json_error('Users table does not exist');
        }

        // Get current user UID if provided to exclude them
        $current_user_uid = isset($_POST['current_user_uid']) ? sanitize_text_field(wp_unslash($_POST['current_user_uid'])) : '';

        if (!empty($current_user_uid)) {
            $users = $wpdb->get_results(
                $wpdb->prepare(
                    "SELECT * FROM $table_users WHERE firebase_uid != %s ORDER BY last_seen DESC",
                    $current_user_uid
                )
            );
        } else {
            $users = $wpdb->get_results(
                "SELECT * FROM $table_users ORDER BY last_seen DESC"
            );
        }

        if ($users === false) {
            wp_send_json_error('Failed to retrieve users');
        }

        $formatted_users = [];
        foreach ($users as $user) {
            // Check if user is online (last seen within 2 minutes)
            $last_seen_time = strtotime($user->last_seen);
            $is_online = (time() - $last_seen_time) < 120; // 2 minutes
            
            $formatted_users[] = [
                'id' => absint($user->id),
                'firebase_uid' => esc_html($user->firebase_uid),
                'user_name' => esc_html($user->user_name),
                'user_email' => esc_html($user->user_email),
                'user_avatar' => esc_url($user->user_avatar),
                'auth_provider' => esc_html($user->auth_provider),
                'is_admin' => (bool) $user->is_admin,
                'is_online' => $is_online,
                'last_seen' => esc_html($user->last_seen),
                'created_at' => esc_html($user->created_at),
                'formatted_last_seen' => esc_html(date('M d, Y > h:i A', strtotime($user->last_seen)))
            ];
        }

        wp_send_json_success([
            'users' => $formatted_users,
            'total' => count($formatted_users),
            'timestamp' => time()
        ]);
    }

    /**
     * Sync Firebase users to WordPress database - Only for administrators
     * This endpoint receives Firebase user data from the React frontend
     */
    public function sync_firebase_users() {
        // Verify nonce
         if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'acb_nonce' ) ) {
			wp_send_json_error([
				'message' => __( 'Security check failed.', 'acb' ),
			]);
		}

        // Check user permissions - Only administrators can sync users
        if (!current_user_can('manage_options')) {
            wp_send_json_error('Insufficient permissions - Only administrators can sync users');
        }

        // Get Firebase users data from POST
        if (!isset($_POST['firebase_users']) || empty($_POST['firebase_users'])) {
            wp_send_json_error('No Firebase users data provided');
        }

        $firebase_users_json = wp_unslash($_POST['firebase_users']);
        $firebase_users = json_decode($firebase_users_json, true);

        if (!is_array($firebase_users)) {
            wp_send_json_error('Invalid Firebase users data format');
        }

        $synced_count = 0;
        $errors = [];

        foreach ($firebase_users as $fb_user) {
            // Validate required fields
            if (!isset($fb_user['uid']) || !isset($fb_user['email'])) {
                $errors[] = 'Missing required fields for user: ' . ($fb_user['email'] ?? 'unknown');
                continue;
            }

            // Sanitize user data
            $firebase_uid = sanitize_text_field($fb_user['uid']);
            $user_name = sanitize_text_field($fb_user['displayName'] ?? $fb_user['email']);
            $user_email = sanitize_email($fb_user['email']);
            $user_avatar = isset($fb_user['photoURL']) ? esc_url_raw($fb_user['photoURL']) : '';
            $auth_provider = sanitize_text_field($fb_user['auth_provider'] ?? 'firebase');

            // Add user to chat table
            $result = $this->add_user_to_chat_table($firebase_uid, $user_name, $user_email, $user_avatar, $auth_provider);
            
            if ($result !== false) {
                $synced_count++;
            } else {
                $errors[] = 'Failed to sync user: ' . $user_email;
            }
        }

        if ($synced_count > 0) {
            wp_send_json_success([
                'message' => "Successfully synced {$synced_count} users",
                'synced_count' => $synced_count,
                'errors' => $errors
            ]);
        } else {
            wp_send_json_error('No users were synced. Errors: ' . implode(', ', $errors));
        }
    }

    /**
     * Add user to chat users table
     */
    private function add_user_to_chat_table($firebase_uid, $user_name, $user_email, $user_avatar, $auth_provider) {
        global $wpdb;
        $table_users = $wpdb->prefix . 'acb_users';
        
        // Validate table exists
        if ($wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $table_users)) !== $table_users) {
            error_log('ACB: Chat users table does not exist: ' . $table_users);
            return false;
        }
        
        // Check if user already exists in chat table
        $existing_user = $wpdb->get_row(
            $wpdb->prepare("SELECT * FROM $table_users WHERE firebase_uid = %s", $firebase_uid)
        );
        
        if ($existing_user) {
            // Update existing user
            $result = $wpdb->update(
                $table_users,
                [
                    'user_name' => $user_name,
                    'user_email' => $user_email,
                    'user_avatar' => $user_avatar,
                    'auth_provider' => $auth_provider,
                    'last_seen' => current_time('mysql'),
                    'updated_at' => current_time('mysql')
                ],
                ['firebase_uid' => $firebase_uid],
                ['%s', '%s', '%s', '%s', '%s', '%s'],
                ['%s']
            );
            
            if ($result !== false) {
                error_log('ACB: Updated existing chat user: ' . $user_email);
                return $existing_user->id;
            }
        } else {
            // Create new user in chat table
            $result = $wpdb->insert(
                $table_users,
                [
                    'firebase_uid' => $firebase_uid,
                    'user_name' => $user_name,
                    'user_email' => $user_email,
                    'user_avatar' => $user_avatar,
                    'auth_provider' => $auth_provider,
                    'is_admin' => 0, // Default to regular user
                    'last_seen' => current_time('mysql'),
                    'created_at' => current_time('mysql'),
                    'updated_at' => current_time('mysql')
                ],
                ['%s', '%s', '%s', '%s', '%s', '%d', '%s', '%s', '%s']
            );
            
            if ($result !== false) {
                $new_user_id = $wpdb->insert_id;
                error_log('ACB: Created new chat user: ' . $user_email . ' (ID: ' . $new_user_id . ')');
                return $new_user_id;
            }
        }
        
        error_log('ACB: Failed to add/update user in chat table: ' . $user_email);
        return false;
    }

    /**
     * Check if user is admin in chat system - Available to all users
     */
    public function check_user_admin_status() {
        // Verify nonce
         if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'acb_nonce' ) ) {
			wp_send_json_error([
				'message' => __( 'Security check failed.', 'acb' ),
			]);
		}

        // Validate required fields
        if (!isset($_POST['firebase_uid']) || empty(trim($_POST['firebase_uid']))) {
            wp_send_json_error('Firebase UID is required');
        }

        $firebase_uid = sanitize_text_field(wp_unslash($_POST['firebase_uid']));

        global $wpdb;
        $table_users = $wpdb->prefix . 'acb_users';
        
        // Validate table exists
        if ($wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $table_users)) !== $table_users) {
            wp_send_json_error('Users table does not exist');
        }

        // Get user from database
        $user = $wpdb->get_row(
            $wpdb->prepare("SELECT * FROM $table_users WHERE firebase_uid = %s", $firebase_uid)
        );

        if (!$user) {
            // User not found in database, they are regular by default
            wp_send_json_success([
                'is_admin' => false,
                'message' => 'User not found in database, defaulting to regular user'
            ]);
        } else {
            wp_send_json_success([
                'is_admin' => (bool) $user->is_admin,
                'user_id' => absint($user->id),
                'user_name' => esc_html($user->user_name)
            ]);
        }
    }
  
    /**
     * Get frontend widget settings - Available to all users
     */
    public function get_widget_settings() {
        // Verify nonce
         if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'acb_nonce' ) ) {
			wp_send_json_error([
				'message' => __( 'Security check failed.', 'acb' ),
			]);
		}

        global $wpdb;
        $table_settings = $wpdb->prefix . 'acb_settings';
        
        // Get widget settings from database
        $widget_settings = [];
        $settings_keys = [
            'frontend_widget_enabled',
            'widget_position', 
            'widget_title',
            'widget_description',
            'widget_primary_color',
            'widget_show_on_pages',
            'widget_exclude_pages'
        ];
        
        // Default values
        $defaults = [
            'frontend_widget_enabled' => true,
            'widget_position' => 'bottom-right',
            'widget_title' => 'Chat Support',
            'widget_description' => 'Need help? Chat with our team!',
            'widget_primary_color' => '#5A5EB9',
            'widget_show_on_pages' => 'all',
            'widget_exclude_pages' => ''
        ];
        
        foreach ($settings_keys as $key) {
            $value = $wpdb->get_var(
                $wpdb->prepare("SELECT setting_value FROM $table_settings WHERE setting_key = %s", $key)
            );
            
            // Handle boolean conversion for frontend_widget_enabled
            if ($key === 'frontend_widget_enabled') {
                if ($value !== null) {
                    $widget_settings[$key] = ($value === '1' || $value === 'true' || $value === true || $value === 1);
                } else {
                    $widget_settings[$key] = $defaults[$key];
                }
            } else {
                // Use database value if exists, otherwise use default
                $widget_settings[$key] = $value !== null ? $value : $defaults[$key];
            }
        }

        wp_send_json_success([
            'widget_settings' => $widget_settings
        ]);
    }

    /**
     * Save frontend widget settings - Only for administrators
     */
    public function save_widget_settings() {
        // Verify nonce
         if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'acb_nonce' ) ) {
			wp_send_json_error([
				'message' => __( 'Security check failed.', 'acb' ),
			]);
		}

        // Check user permissions - Only administrators can save widget settings
        if (!current_user_can('manage_options')) {
            wp_send_json_error('Insufficient permissions - Only administrators can save widget settings');
        }

        // Get and validate settings
        $settings = [];
        $allowed_settings = [
            'frontend_widget_enabled',
            'widget_position',
            'widget_title',
            'widget_description', 
            'widget_primary_color',
            'widget_show_on_pages',
            'widget_exclude_pages'
        ];

        foreach ($allowed_settings as $key) {
            if (isset($_POST[$key])) {
                $settings[$key] = sanitize_text_field(wp_unslash($_POST[$key]));
            }
        }

        // Validate specific settings
        if (isset($settings['widget_position'])) {
            $allowed_positions = ['bottom-right', 'bottom-left', 'top-right', 'top-left'];
            if (!in_array($settings['widget_position'], $allowed_positions, true)) {
                wp_send_json_error('Invalid widget position');
            }
        }

        if (isset($settings['widget_show_on_pages'])) {
            $allowed_show_options = ['all', 'specific', 'exclude'];
            if (!in_array($settings['widget_show_on_pages'], $allowed_show_options, true)) {
                wp_send_json_error('Invalid show on pages option');
            }
        }

        // Save settings to database
        global $wpdb;
        $table_settings = $wpdb->prefix . 'acb_settings';
        $saved_count = 0;

        foreach ($settings as $key => $value) {
            $result = $wpdb->replace(
                $table_settings,
                [
                    'setting_key' => $key,
                    'setting_value' => $value,
                    'updated_at' => current_time('mysql')
                ],
                ['%s', '%s', '%s']
            );
            
            if ($result !== false) {
                $saved_count++;
            }
        }

        if ($saved_count > 0) {
            wp_send_json_success([
                'message' => 'Widget settings saved successfully',
                'saved_count' => $saved_count
            ]);
        } else {
            wp_send_json_error('Failed to save widget settings');
        }
    }


}