prefix . 'cloudprime_chat_logs'; $charset_collate = $wpdb->get_charset_collate(); $sql = "CREATE TABLE $table_name ( id mediumint(9) NOT NULL AUTO_INCREMENT, session_id varchar(32) NOT NULL, user_message text NOT NULL, ai_response text NOT NULL, contact_info text DEFAULT NULL, whmcs_client_id int DEFAULT NULL, ai_provider varchar(20) DEFAULT 'openrouter', created_at datetime DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (id) ) $charset_collate;"; require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); dbDelta($sql); // Contacts table $table_name = $wpdb->prefix . 'cloudprime_contacts'; $sql = "CREATE TABLE $table_name ( id mediumint(9) NOT NULL AUTO_INCREMENT, session_id varchar(32) NOT NULL, name varchar(255) NOT NULL, phone varchar(50) NOT NULL, email varchar(255) DEFAULT NULL, whmcs_client_id int DEFAULT NULL, source varchar(50) DEFAULT 'chatbot', created_at datetime DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (id) ) $charset_collate;"; dbDelta($sql); cloudprime_debug_log('Enhanced tables created with WHMCS integration'); } // Admin menu add_action('admin_menu', function() { add_menu_page( 'CloudPrime Chatbot', 'CloudPrime Chatbot', 'manage_options', 'cloudprime-chatbot', 'cloudprime_chatbot_admin_page_content', 'dashicons-format-chat', 6 ); add_submenu_page( 'cloudprime-chatbot', 'Chat Logs', 'Chat Logs', 'manage_options', 'cloudprime-chat-logs', 'cloudprime_chatbot_logs_page' ); add_submenu_page( 'cloudprime-chatbot', 'Contacts', 'Contacts', 'manage_options', 'cloudprime-contacts', 'cloudprime_chatbot_contacts_page' ); add_submenu_page( 'cloudprime-chatbot', 'WHMCS Settings', 'WHMCS Settings', 'manage_options', 'cloudprime-whmcs', 'cloudprime_whmcs_settings_page' ); }); function cloudprime_chatbot_admin_page_content() { // Handle form submission if (isset($_POST['submit'])) { $settings = [ 'ai_provider' => sanitize_text_field($_POST['ai_provider'] ?? 'openrouter'), 'openrouter_api_key' => sanitize_text_field($_POST['openrouter_api_key'] ?? ''), 'gemini_api_key' => sanitize_text_field($_POST['gemini_api_key'] ?? ''), 'whatsapp_number' => sanitize_text_field($_POST['whatsapp_number'] ?? ''), 'ai_name' => sanitize_text_field($_POST['ai_name'] ?? 'CloudPrime Assistant'), 'ai_avatar_url' => esc_url_raw($_POST['ai_avatar_url'] ?? ''), 'predefined_questions_setting' => sanitize_textarea_field($_POST['predefined_questions_setting'] ?? ''), 'enable_conditional_whatsapp' => isset($_POST['enable_conditional_whatsapp']) ? 1 : 0, 'notification_email' => sanitize_email($_POST['notification_email'] ?? get_option('admin_email')), 'enable_whmcs_integration' => isset($_POST['enable_whmcs_integration']) ? 1 : 0, 'enable_voice_commands' => isset($_POST['enable_voice_commands']) ? 1 : 0 ]; update_option('cloudprime_chatbot_settings', $settings); echo '

Settings saved successfully!

'; } $opts = get_option('cloudprime_chatbot_settings', []); ?>

CloudPrime Chatbot Settings

Debug Information

Plugin Status: Not configured (API key missing)' : 'Configured (' . $provider . ')'; ?>

WHMCS Integration: Enabled' : 'Disabled'; ?>

Voice Commands: Enabled' : 'Disabled'; ?>

Current Theme:

AI Provider

Choose your preferred AI provider.

OpenRouter API Key

Get a key from openrouter.ai

Google Gemini API Key

Get a key from Google AI Studio

WhatsApp Number

Format: 27101108466 (no spaces or special chars)

AI Name

The name displayed for the AI chatbot.

AI Avatar URL

URL to the AI's avatar image.

Predefined Questions

Enter each question on a new line.

Enable Conditional WhatsApp Button >

If enabled, the WhatsApp button will only appear when the AI cannot answer a question or when the client asks to speak to a human.

Enable Voice Commands >

Enable voice recognition for hands-free interaction.

Enable WHMCS Integration >

Enable integration with WHMCS for client support features.

Notification Email

Email address to receive new contact notifications.

esc_url_raw($_POST['whmcs_url'] ?? ''), 'whmcs_api_identifier' => sanitize_text_field($_POST['whmcs_api_identifier'] ?? ''), 'whmcs_api_secret' => sanitize_text_field($_POST['whmcs_api_secret'] ?? ''), 'whmcs_db_host' => sanitize_text_field($_POST['whmcs_db_host'] ?? ''), 'whmcs_db_name' => sanitize_text_field($_POST['whmcs_db_name'] ?? ''), 'whmcs_db_user' => sanitize_text_field($_POST['whmcs_db_user'] ?? ''), 'whmcs_db_pass' => sanitize_text_field($_POST['whmcs_db_pass'] ?? ''), 'whmcs_integration_method' => sanitize_text_field($_POST['whmcs_integration_method'] ?? 'api') ]; update_option('cloudprime_whmcs_settings', $whmcs_settings); echo '

WHMCS settings saved successfully!

'; } $whmcs_opts = get_option('cloudprime_whmcs_settings', []); ?>

WHMCS Integration Settings

Integration Method

Choose how to connect to WHMCS.

WHMCS URL

Your WHMCS installation URL (e.g., https://billing.cloudprime.co.za)

API Identifier

WHMCS API Identifier from Setup > General Settings > Security

API Secret

WHMCS API Secret

Database Host

WHMCS database host (usually localhost)

Database Name

WHMCS database name

Database Username

WHMCS database username

Database Password

WHMCS database password

get_results("SELECT * FROM {$wpdb->prefix}cloudprime_chat_logs ORDER BY created_at DESC LIMIT 100"); ?>

Chat Logs

Date Session ID User Message AI Response AI Provider WHMCS Client Contact Info
created_at); ?> session_id, 0, 8)); ?>... user_message, 10)); ?> ai_response, 15)); ?> ai_provider ?? 'openrouter'); ?> whmcs_client_id ? esc_html($log->whmcs_client_id) : '-'; ?> contact_info); ?>
get_results("SELECT * FROM {$wpdb->prefix}cloudprime_contacts ORDER BY created_at DESC"); ?>

Contacts

Date Name Phone Email WHMCS Client ID Source
created_at); ?> name); ?> phone); ?> email); ?> whmcs_client_id ? esc_html($contact->whmcs_client_id) : '-'; ?> source); ?>
'GetClientsDetails', 'email' => $email, 'identifier' => $identifier, 'secret' => $secret, 'responsetype' => 'json' ]; $response = wp_remote_post($url . '/includes/api.php', [ 'body' => $postdata, 'timeout' => 10 ]); if (is_wp_error($response)) { cloudprime_debug_log('WHMCS API Error: ' . $response->get_error_message()); return null; } $result = json_decode(wp_remote_retrieve_body($response), true); if (isset($result['result']) && $result['result'] === 'success') { return $result; } return null; } function cloudprime_whmcs_db_get_client($email) { $whmcs_opts = get_option('cloudprime_whmcs_settings', []); $host = $whmcs_opts['whmcs_db_host'] ?? ''; $dbname = $whmcs_opts['whmcs_db_name'] ?? ''; $username = $whmcs_opts['whmcs_db_user'] ?? ''; $password = $whmcs_opts['whmcs_db_pass'] ?? ''; if (empty($host) || empty($dbname) || empty($username)) { return null; } try { $whmcs_db = new PDO("mysql:host=$host;dbname=$dbname", $username, $password); $whmcs_db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $stmt = $whmcs_db->prepare("SELECT * FROM tblclients WHERE email = ?"); $stmt->execute([$email]); $client = $stmt->fetch(PDO::FETCH_ASSOC); if ($client) { // Get recent invoices $stmt = $whmcs_db->prepare("SELECT * FROM tblinvoices WHERE userid = ? ORDER BY id DESC LIMIT 5"); $stmt->execute([$client['id']]); $invoices = $stmt->fetchAll(PDO::FETCH_ASSOC); // Get recent tickets $stmt = $whmcs_db->prepare("SELECT * FROM tbltickets WHERE userid = ? ORDER BY id DESC LIMIT 5"); $stmt->execute([$client['id']]); $tickets = $stmt->fetchAll(PDO::FETCH_ASSOC); return [ 'client' => $client, 'invoices' => $invoices, 'tickets' => $tickets ]; } } catch (PDOException $e) { cloudprime_debug_log('WHMCS DB Error: ' . $e->getMessage()); } return null; } // Enhanced AI Chat Function function cloudprime_get_ai_response($prompt, $client_data = null, $provider = 'openrouter') { $opt = get_option('cloudprime_chatbot_settings'); if ($provider === 'gemini') { return cloudprime_get_gemini_response($prompt, $client_data, $opt); } else { return cloudprime_get_openrouter_response($prompt, $client_data, $opt); } } function cloudprime_get_gemini_response($prompt, $client_data, $opt) { $api_key = $opt['gemini_api_key'] ?? ''; if (empty($api_key)) { return ['error' => 'Gemini API key not configured']; } $sys_prompt = cloudprime_build_system_prompt($client_data); $body = json_encode([ 'contents' => [ [ 'parts' => [ ['text' => $sys_prompt . "\n\nUser: " . $prompt] ] ] ], 'generationConfig' => [ 'temperature' => 0.7, 'maxOutputTokens' => 300 ] ]); $response = wp_remote_post("https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash-latest:generateContent?key=" . $api_key, [ 'headers' => [ 'Content-Type' => 'application/json' ], 'body' => $body, 'timeout' => 20 ]); if (is_wp_error($response)) { return ['error' => $response->get_error_message()]; } $result = json_decode(wp_remote_retrieve_body($response), true); if (isset($result['candidates'][0]['content']['parts'][0]['text'])) { return ['reply' => $result['candidates'][0]['content']['parts'][0]['text']]; } return ['error' => 'Invalid Gemini API response']; } function cloudprime_get_openrouter_response($prompt, $client_data, $opt) { $api_key = $opt['openrouter_api_key'] ?? ''; if (empty($api_key)) { return ['error' => 'OpenRouter API key not configured']; } $sys_prompt = cloudprime_build_system_prompt($client_data); $body = json_encode([ "model" => "openrouter/auto", "max_tokens" => 300, "temperature" => 0.7, "messages" => [ ["role" => "system", "content" => $sys_prompt], ["role" => "user", "content" => $prompt] ] ]); $response = wp_remote_post("https://openrouter.ai/api/v1/chat/completions", [ "headers" => [ "Authorization" => "Bearer $api_key", "Content-Type" => "application/json" ], "body" => $body, "timeout" => 20 ]); if (is_wp_error($response)) { return ['error' => $response->get_error_message()]; } $result = json_decode(wp_remote_retrieve_body($response), true); if (isset($result['choices'][0]['message']['content'])) { return ['reply' => $result['choices'][0]['message']['content']]; } return ['error' => 'Invalid OpenRouter API response']; } function cloudprime_build_system_prompt($client_data = null) { $base_prompt = "You are a helpful assistant for Cloud Prime Connect (cloudprime.co.za), an IT and telecom services provider based in Johannesburg, South Africa. CloudPrime offers: - Managed IT services (24/7 monitoring, cybersecurity, helpdesk support) - Fibre and LTE connectivity solutions - Yeastar PBX and VoIP systems - Hotspot installations and WiFi solutions - Data management and IT consulting - Cloud services and hosting - Network security solutions Contact information: - Website: cloudprime.co.za/contact - Phone: +27 10 110 8466 - Email: info@cloudprime.co.za"; if ($client_data && isset($client_data['client'])) { $client = $client_data['client']; $base_prompt .= "\n\nCLIENT INFORMATION:\n"; $base_prompt .= "- Client Name: " . $client['firstname'] . " " . $client['lastname'] . "\n"; $base_prompt .= "- Email: " . $client['email'] . "\n"; $base_prompt .= "- Client ID: " . $client['id'] . "\n"; $base_prompt .= "- Status: " . $client['status'] . "\n"; if (!empty($client_data['invoices'])) { $base_prompt .= "\nRECENT INVOICES:\n"; foreach (array_slice($client_data['invoices'], 0, 3) as $invoice) { $base_prompt .= "- Invoice #" . $invoice['invoicenum'] . " - " . $invoice['status'] . " - R" . $invoice['total'] . "\n"; } } if (!empty($client_data['tickets'])) { $base_prompt .= "\nRECENT SUPPORT TICKETS:\n"; foreach (array_slice($client_data['tickets'], 0, 3) as $ticket) { $base_prompt .= "- Ticket #" . $ticket['tid'] . " - " . $ticket['subject'] . " - " . $ticket['status'] . "\n"; } } $base_prompt .= "\nYou can reference this client information when helping them with their inquiries."; } $base_prompt .= "\n\nBe helpful, professional, and if you cannot answer a question or if they need human assistance, suggest they contact CloudPrime directly or ask to speak to a human agent."; return $base_prompt; } // AJAX handlers add_action('wp_ajax_cloudprime_chat', 'cloudprime_handle_chat_ajax'); add_action('wp_ajax_nopriv_cloudprime_chat', 'cloudprime_handle_chat_ajax'); function cloudprime_handle_chat_ajax() { check_ajax_referer('cloudprime_chat_nonce', 'nonce'); $message = sanitize_text_field($_POST['message']); $session_id = sanitize_text_field($_POST['session_id']); $email = sanitize_email($_POST['email'] ?? ''); $opts = get_option('cloudprime_chatbot_settings'); $provider = $opts['ai_provider'] ?? 'openrouter'; // Get client data if email provided and WHMCS integration is enabled $client_data = null; $whmcs_client_id = null; if (!empty($email) && !empty($opts['enable_whmcs_integration'])) { $client_data = cloudprime_get_whmcs_client_by_email($email); if ($client_data && isset($client_data['client'])) { $whmcs_client_id = $client_data['client']['id']; } } // Get AI response $ai_response = cloudprime_get_ai_response($message, $client_data, $provider); if (isset($ai_response['error'])) { wp_send_json_error($ai_response['error']); return; } $response_text = $ai_response['reply']; // Log the conversation global $wpdb; $wpdb->insert( $wpdb->prefix . 'cloudprime_chat_logs', [ 'session_id' => $session_id, 'user_message' => $message, 'ai_response' => $response_text, 'contact_info' => $email, 'whmcs_client_id' => $whmcs_client_id, 'ai_provider' => $provider, 'created_at' => current_time('mysql') ] ); // Check if we should show WhatsApp button $show_whatsapp = false; if (!empty($opts['enable_conditional_whatsapp'])) { $trigger_phrases = ['speak to human', 'human agent', 'contact support', 'call you', 'cannot help', 'don\'t know']; foreach ($trigger_phrases as $phrase) { if (stripos($response_text, $phrase) !== false || stripos($message, $phrase) !== false) { $show_whatsapp = true; break; } } } wp_send_json_success([ 'message' => $response_text, 'show_whatsapp' => $show_whatsapp, 'client_info' => $client_data ? [ 'name' => $client_data['client']['firstname'] . ' ' . $client_data['client']['lastname'], 'client_id' => $client_data['client']['id'], 'status' => $client_data['client']['status'] ] : null ]); } // Save contact info add_action('wp_ajax_cloudprime_save_contact', 'cloudprime_save_contact_ajax'); add_action('wp_ajax_nopriv_cloudprime_save_contact', 'cloudprime_save_contact_ajax'); function cloudprime_save_contact_ajax() { check_ajax_referer('cloudprime_chat_nonce', 'nonce'); $name = sanitize_text_field($_POST['name']); $phone = sanitize_text_field($_POST['phone']); $email = sanitize_email($_POST['email']); $session_id = sanitize_text_field($_POST['session_id']); // Check if this is a WHMCS client $whmcs_client_id = null; $opts = get_option('cloudprime_chatbot_settings'); if (!empty($opts['enable_whmcs_integration']) && !empty($email)) { $client_data = cloudprime_get_whmcs_client_by_email($email); if ($client_data && isset($client_data['client'])) { $whmcs_client_id = $client_data['client']['id']; } } global $wpdb; $result = $wpdb->insert( $wpdb->prefix . 'cloudprime_contacts', [ 'session_id' => $session_id, 'name' => $name, 'phone' => $phone, 'email' => $email, 'whmcs_client_id' => $whmcs_client_id, 'source' => 'chatbot', 'created_at' => current_time('mysql') ] ); if ($result) { // Send notification email $notification_email = $opts['notification_email'] ?? get_option('admin_email'); $subject = 'New Contact from CloudPrime Chatbot'; $message = "New contact submitted via chatbot:\n\n"; $message .= "Name: $name\n"; $message .= "Phone: $phone\n"; $message .= "Email: $email\n"; if ($whmcs_client_id) { $message .= "WHMCS Client ID: $whmcs_client_id\n"; } $message .= "Session ID: $session_id\n"; $message .= "Date: " . current_time('mysql') . "\n"; wp_mail($notification_email, $subject, $message); wp_send_json_success([ 'message' => 'Thank you! Your contact information has been saved.', 'predefined_questions' => array_filter(explode("\n", $opts['predefined_questions_setting'] ?? '')) ]); } else { wp_send_json_error('Failed to save contact information'); } } // Frontend chatbot display add_action('wp_footer', 'cloudprime_chatbot_frontend'); function cloudprime_chatbot_frontend() { $opts = get_option('cloudprime_chatbot_settings'); $provider = $opts['ai_provider'] ?? 'openrouter'; // Check if API key is configured $api_key_field = $provider === 'gemini' ? 'gemini_api_key' : 'openrouter_api_key'; if (empty($opts[$api_key_field])) { return; // Don't show chatbot if not configured } $ai_name = $opts['ai_name'] ?? 'CloudPrime Assistant'; $ai_avatar = $opts['ai_avatar_url'] ?? ''; $whatsapp_number = $opts['whatsapp_number'] ?? ''; $predefined_questions = array_filter(explode("\n", $opts['predefined_questions_setting'] ?? '')); $enable_voice = !empty($opts['enable_voice_commands']); ?>
💬