<?php
if ( ! defined( 'ABSPATH' ) ) exit;

/**
 * AI Website Chat Assistant
 * Intelligent chat assistant that integrates into generated websites
 */

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

class VMO_Website_AI_Assistant {
    
    private $api_key;
    private $assistant_settings;
    
    public function __construct() {
        $this->api_key = get_option('vmo_openai_api_key');
        $this->assistant_settings = $this->get_assistant_settings();
        
        // Setup AJAX handlers for the chat assistant
        add_action('wp_ajax_vmo_website_chat', array($this, 'process_website_chat'));
        add_action('wp_ajax_nopriv_vmo_website_chat', array($this, 'process_website_chat'));
        
        // Add assistant to generated websites
        add_action('wp_footer', array($this, 'add_chat_assistant_to_website'));
    }
    
    /**
     * Get assistant settings for the current website
     */
    private function get_assistant_settings() {
        // This would be customized per website/business
        return array(
            'business_name' => get_bloginfo('name'),
            'business_description' => get_bloginfo('description'),
            'assistant_name' => get_option('vmo_assistant_name', 'AI Assistant'),
            'primary_color' => get_option('vmo_assistant_color', '#00ffff'),
            'logo_url' => get_option('vmo_assistant_logo', ''),
            'enabled_features' => array(
                'general_inquiries' => true,
                'appointment_booking' => get_option('vmo_assistant_booking', false),
                'product_support' => get_option('vmo_assistant_support', true),
                'sales_assistance' => get_option('vmo_assistant_sales', true),
                'lead_capture' => get_option('vmo_assistant_leads', true)
            ),
            'business_hours' => get_option('vmo_business_hours', '9 AM - 5 PM Monday-Friday'),
            'contact_info' => array(
                'phone' => get_option('vmo_business_phone', ''),
                'email' => get_option('vmo_business_email', get_option('admin_email')),
                'address' => get_option('vmo_business_address', '')
            )
        );
    }
    
    /**
     * Add chat assistant widget to website footer
     */
    public function add_chat_assistant_to_website() {
        // Only add to non-admin pages on VMO-generated websites
        if (is_admin() || !$this->is_vmo_generated_site()) {
            return;
        }
        
        $this->render_chat_widget();
        $this->enqueue_chat_assets();
    }
    
    /**
     * Check if current site is VMO-generated (simple check)
     */
    private function is_vmo_generated_site() {
        // Check if site has VMO-generated content markers
        $template = (string) get_option('template', '');
        return get_option('vmo_website_generated', false) || 
               strpos($template, 'vmo-') !== false ||
               get_option('vmo_enable_chat_assistant', false);
    }
    
    /**
     * Render chat widget HTML
     */
    private function render_chat_widget() {
        $settings = $this->assistant_settings;
        $logo_url = $settings['logo_url'] ?: (VMO_AI_BUILDER_URL . 'assets/vmo-icon.svg');
        ?>
        
        <!-- VMO AI Chat Assistant Widget -->
        <div id="vmo-chat-widget" class="vmo-chat-widget" style="display: none;">
            <div class="vmo-chat-header">
                <div class="vmo-chat-avatar">
                    <img src="<?php echo esc_url($logo_url); ?>" alt="Assistant" />
                </div>
                <div class="vmo-chat-info">
                    <div class="vmo-chat-title"><?php echo esc_html($settings['assistant_name']); ?></div>
                    <div class="vmo-chat-subtitle">How can I help you today?</div>
                </div>
                <button class="vmo-chat-close" id="vmo-chat-close">×</button>
            </div>
            
            <div class="vmo-chat-messages" id="vmo-chat-messages">
                <div class="vmo-chat-message vmo-chat-ai">
                    <div class="vmo-message-avatar">
                        <img src="<?php echo esc_url($logo_url); ?>" alt="AI" />
                    </div>
                    <div class="vmo-message-content">
                        <p>Hello! I'm here to help you with information about <?php echo esc_html($settings['business_name']); ?>. I can assist with:</p>
                        <ul>
                            <?php if ($settings['enabled_features']['general_inquiries']): ?>
                                <li>General questions about our services</li>
                            <?php endif; ?>
                            <?php if ($settings['enabled_features']['appointment_booking']): ?>
                                <li>Booking appointments</li>
                            <?php endif; ?>
                            <?php if ($settings['enabled_features']['product_support']): ?>
                                <li>Product information and support</li>
                            <?php endif; ?>
                            <?php if ($settings['enabled_features']['sales_assistance']): ?>
                                <li>Sales inquiries and pricing</li>
                            <?php endif; ?>
                            <?php if ($settings['enabled_features']['lead_capture']): ?>
                                <li>Connecting you with our team</li>
                            <?php endif; ?>
                        </ul>
                        <p>What would you like to know?</p>
                    </div>
                </div>
            </div>
            
            <div class="vmo-chat-input-area">
                <div class="vmo-chat-input-container">
                    <textarea id="vmo-chat-input" 
                              placeholder="Type your message here..." 
                              rows="1"></textarea>
                    <button id="vmo-chat-send" class="vmo-chat-send-btn">
                        <svg viewBox="0 0 24 24" width="20" height="20">
                            <path fill="currentColor" d="M2,21L23,12L2,3V10L17,12L2,14V21Z"/>
                        </svg>
                    </button>
                </div>
                <div class="vmo-chat-suggestions">
                    <button class="vmo-suggestion-btn" data-message="What are your business hours?">Business Hours</button>
                    <button class="vmo-suggestion-btn" data-message="How can I contact you?">Contact Info</button>
                    <?php if ($settings['enabled_features']['appointment_booking']): ?>
                        <button class="vmo-suggestion-btn" data-message="I'd like to book an appointment">Book Appointment</button>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        
        <!-- Chat Toggle Button -->
        <div class="vmo-chat-toggle" id="vmo-chat-toggle">
            <div class="vmo-chat-toggle-icon">
                <svg viewBox="0 0 24 24" width="24" height="24">
                    <path fill="currentColor" d="M12,2C6.48,2 2,6.48 2,12C2,13.54 2.36,15.02 3.04,16.34L2,22L7.66,20.96C8.98,21.64 10.46,22 12,22C17.52,22 22,17.52 22,12C22,6.48 17.52,2 12,2ZM12,20C10.69,20 9.45,19.72 8.34,19.2L8,19L4.5,20L5.5,16.5L5.3,16.16C4.78,15.05 4.5,13.81 4.5,12.5C4.5,7.86 8.36,4 13,4C17.64,4 21.5,7.86 21.5,12.5C21.5,17.14 17.64,21 13,21H12Z"/>
                </svg>
            </div>
            <div class="vmo-chat-notification" id="vmo-chat-notification">1</div>
        </div>
        
        <?php
    }
    
    /**
     * Enqueue chat widget assets
     */
    private function enqueue_chat_assets() {
        $settings = $this->assistant_settings;
        ?>
        
        <style>
        /* VMO AI Chat Assistant Styles */
        .vmo-chat-widget {
            position: fixed;
            bottom: 100px;
            right: 20px;
            width: 380px;
            max-width: calc(100vw - 40px);
            height: 500px;
            max-height: calc(100vh - 140px);
            background: #ffffff;
            border-radius: 16px;
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
            z-index: 10000;
            display: flex;
            flex-direction: column;
            overflow: hidden;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
        }
        
        .vmo-chat-header {
            background: <?php echo esc_attr($settings['primary_color']); ?>;
            color: white;
            padding: 16px;
            display: flex;
            align-items: center;
            gap: 12px;
            min-height: 60px;
        }
        
        .vmo-chat-avatar img {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            object-fit: cover;
            background: rgba(255, 255, 255, 0.2);
        }
        
        .vmo-chat-info {
            flex: 1;
        }
        
        .vmo-chat-title {
            font-weight: 600;
            font-size: 16px;
            margin: 0;
        }
        
        .vmo-chat-subtitle {
            font-size: 13px;
            opacity: 0.9;
            margin: 2px 0 0 0;
        }
        
        .vmo-chat-close {
            background: none;
            border: none;
            color: white;
            font-size: 24px;
            cursor: pointer;
            padding: 4px;
            border-radius: 4px;
            opacity: 0.8;
            transition: opacity 0.2s;
        }
        
        .vmo-chat-close:hover {
            opacity: 1;
            background: rgba(255, 255, 255, 0.1);
        }
        
        .vmo-chat-messages {
            flex: 1;
            padding: 16px;
            overflow-y: auto;
            scroll-behavior: smooth;
        }
        
        .vmo-chat-message {
            margin-bottom: 16px;
            display: flex;
            gap: 8px;
        }
        
        .vmo-chat-user {
            justify-content: flex-end;
        }
        
        .vmo-chat-ai .vmo-message-avatar img {
            width: 30px;
            height: 30px;
            border-radius: 50%;
            object-fit: cover;
        }
        
        .vmo-message-content {
            max-width: 280px;
            padding: 12px 16px;
            border-radius: 16px;
            font-size: 14px;
            line-height: 1.4;
        }
        
        .vmo-chat-ai .vmo-message-content {
            background: #f5f5f5;
            color: #333;
            border-bottom-left-radius: 4px;
        }
        
        .vmo-chat-user .vmo-message-content {
            background: <?php echo esc_attr($settings['primary_color']); ?>;
            color: white;
            border-bottom-right-radius: 4px;
        }
        
        .vmo-message-content ul {
            margin: 8px 0;
            padding-left: 16px;
        }
        
        .vmo-message-content li {
            margin: 4px 0;
        }
        
        .vmo-chat-input-area {
            padding: 16px;
            background: #f9f9f9;
            border-top: 1px solid #eee;
        }
        
        .vmo-chat-input-container {
            display: flex;
            align-items: flex-end;
            gap: 8px;
            margin-bottom: 8px;
        }
        
        .vmo-chat-input-container textarea {
            flex: 1;
            border: 2px solid #e0e0e0;
            border-radius: 20px;
            padding: 12px 16px;
            font-size: 14px;
            resize: none;
            outline: none;
            transition: border-color 0.2s;
            font-family: inherit;
            max-height: 80px;
        }
        
        .vmo-chat-input-container textarea:focus {
            border-color: <?php echo esc_attr($settings['primary_color']); ?>;
        }
        
        .vmo-chat-send-btn {
            width: 40px;
            height: 40px;
            border: none;
            background: <?php echo esc_attr($settings['primary_color']); ?>;
            color: white;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            transition: all 0.2s;
        }
        
        .vmo-chat-send-btn:hover {
            transform: scale(1.1);
        }
        
        .vmo-chat-send-btn:disabled {
            opacity: 0.5;
            cursor: not-allowed;
            transform: none;
        }
        
        .vmo-chat-suggestions {
            display: flex;
            gap: 8px;
            flex-wrap: wrap;
        }
        
        .vmo-suggestion-btn {
            padding: 6px 12px;
            background: white;
            border: 1px solid #ddd;
            border-radius: 16px;
            font-size: 12px;
            cursor: pointer;
            transition: all 0.2s;
        }
        
        .vmo-suggestion-btn:hover {
            background: <?php echo esc_attr($settings['primary_color']); ?>;
            color: white;
            border-color: <?php echo esc_attr($settings['primary_color']); ?>;
        }
        
        .vmo-chat-toggle {
            position: fixed;
            bottom: 20px;
            right: 20px;
            width: 60px;
            height: 60px;
            background: <?php echo esc_attr($settings['primary_color']); ?>;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            box-shadow: 0 4px 16px rgba(0, 0, 0, 0.2);
            z-index: 10001;
            transition: all 0.3s ease;
            color: white;
        }
        
        .vmo-chat-toggle:hover {
            transform: scale(1.1);
            box-shadow: 0 6px 20px rgba(0, 0, 0, 0.3);
        }
        
        .vmo-chat-notification {
            position: absolute;
            top: -5px;
            right: -5px;
            background: #ff4444;
            color: white;
            border-radius: 50%;
            width: 20px;
            height: 20px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 12px;
            font-weight: 600;
        }
        
        .vmo-typing-indicator {
            display: flex;
            align-items: center;
            gap: 4px;
            padding: 12px 16px;
            background: #f5f5f5;
            border-radius: 16px;
            border-bottom-left-radius: 4px;
            max-width: 60px;
        }
        
        .vmo-typing-dot {
            width: 6px;
            height: 6px;
            background: #999;
            border-radius: 50%;
            animation: vmo-typing 1.4s infinite both;
        }
        
        .vmo-typing-dot:nth-child(1) { animation-delay: -0.32s; }
        .vmo-typing-dot:nth-child(2) { animation-delay: -0.16s; }
        
        @keyframes vmo-typing {
            0%, 80%, 100% { opacity: 0.3; }
            40% { opacity: 1; }
        }
        
        /* Mobile responsive */
        @media (max-width: 480px) {
            .vmo-chat-widget {
                bottom: 90px;
                right: 10px;
                left: 10px;
                width: auto;
                height: 450px;
            }
            
            .vmo-chat-toggle {
                bottom: 15px;
                right: 15px;
                width: 55px;
                height: 55px;
            }
        }
        </style>
        
        <script>
        document.addEventListener('DOMContentLoaded', function() {
            const chatWidget = document.getElementById('vmo-chat-widget');
            const chatToggle = document.getElementById('vmo-chat-toggle');
            const chatClose = document.getElementById('vmo-chat-close');
            const chatMessages = document.getElementById('vmo-chat-messages');
            const chatInput = document.getElementById('vmo-chat-input');
            const chatSend = document.getElementById('vmo-chat-send');
            const chatNotification = document.getElementById('vmo-chat-notification');
            
            let isOpen = false;
            let isTyping = false;
            
            // Toggle chat widget
            chatToggle.addEventListener('click', function() {
                if (isOpen) {
                    closeChat();
                } else {
                    openChat();
                }
            });
            
            // Close chat
            chatClose.addEventListener('click', closeChat);
            
            // Send message on button click
            chatSend.addEventListener('click', sendMessage);
            
            // Send message on Enter key (Shift+Enter for new line)
            chatInput.addEventListener('keydown', function(e) {
                if (e.key === 'Enter' && !e.shiftKey) {
                    e.preventDefault();
                    sendMessage();
                }
            });
            
            // Auto-resize textarea
            chatInput.addEventListener('input', function() {
                this.style.height = 'auto';
                this.style.height = Math.min(this.scrollHeight, 80) + 'px';
            });
            
            // Suggestion buttons
            document.addEventListener('click', function(e) {
                if (e.target.classList.contains('vmo-suggestion-btn')) {
                    const message = e.target.getAttribute('data-message');
                    chatInput.value = message;
                    sendMessage();
                }
            });
            
            function openChat() {
                isOpen = true;
                chatWidget.style.display = 'flex';
                chatNotification.style.display = 'none';
                chatInput.focus();
                
                // Animate in
                chatWidget.style.opacity = '0';
                chatWidget.style.transform = 'translateY(20px) scale(0.95)';
                requestAnimationFrame(function() {
                    chatWidget.style.transition = 'all 0.3s ease';
                    chatWidget.style.opacity = '1';
                    chatWidget.style.transform = 'translateY(0) scale(1)';
                });
            }
            
            function closeChat() {
                isOpen = false;
                chatWidget.style.transition = 'all 0.3s ease';
                chatWidget.style.opacity = '0';
                chatWidget.style.transform = 'translateY(20px) scale(0.95)';
                
                setTimeout(function() {
                    chatWidget.style.display = 'none';
                }, 300);
            }
            
            function sendMessage() {
                const message = chatInput.value.trim();
                if (!message || isTyping) return;
                
                // Add user message to chat
                addMessage(message, 'user');
                chatInput.value = '';
                chatInput.style.height = 'auto';
                
                // Show typing indicator
                showTypingIndicator();
                
                // Send to AI assistant
                fetch('<?php echo admin_url('admin-ajax.php'); ?>', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: new URLSearchParams({
                        action: 'vmo_website_chat',
                        message: message,
                        business_context: JSON.stringify({
                            business_name: '<?php echo esc_js($settings['business_name']); ?>',
                            business_description: '<?php echo esc_js($settings['business_description']); ?>',
                            current_page: window.location.href,
                            page_title: document.title
                        })
                    })
                })
                .then(response => response.json())
                .then(data => {
                    hideTypingIndicator();
                    
                    if (data.success) {
                        addMessage(data.data.response, 'ai');
                        
                        // Handle special actions
                        if (data.data.action) {
                            handleSpecialAction(data.data.action, data.data.actionData);
                        }
                    } else {
                        addMessage('I apologize, but I\'m having trouble responding right now. Please try again later.', 'ai');
                    }
                })
                .catch(error => {
                    hideTypingIndicator();
                    addMessage('I apologize, but I\'m having trouble responding right now. Please try again later.', 'ai');
                });
            }
            
            function addMessage(content, type) {
                const messageDiv = document.createElement('div');
                messageDiv.className = 'vmo-chat-message vmo-chat-' + type;
                
                let messageHTML = '';
                
                if (type === 'ai') {
                    messageHTML = `
                        <div class="vmo-message-avatar">
                            <img src="<?php echo esc_url($logo_url); ?>" alt="AI" />
                        </div>
                        <div class="vmo-message-content">${formatMessage(content)}</div>
                    `;
                } else {
                    messageHTML = `
                        <div class="vmo-message-content">${formatMessage(content)}</div>
                    `;
                }
                
                messageDiv.innerHTML = messageHTML;
                chatMessages.appendChild(messageDiv);
                chatMessages.scrollTop = chatMessages.scrollHeight;
            }
            
            function formatMessage(content) {
                return content
                    .replace(/\n/g, '<br>')
                    .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
                    .replace(/\*(.*?)\*/g, '<em>$1</em>');
            }
            
            function showTypingIndicator() {
                isTyping = true;
                const typingDiv = document.createElement('div');
                typingDiv.className = 'vmo-chat-message vmo-chat-ai';
                typingDiv.id = 'vmo-typing-message';
                typingDiv.innerHTML = `
                    <div class="vmo-message-avatar">
                        <img src="<?php echo esc_url($logo_url); ?>" alt="AI" />
                    </div>
                    <div class="vmo-typing-indicator">
                        <div class="vmo-typing-dot"></div>
                        <div class="vmo-typing-dot"></div>
                        <div class="vmo-typing-dot"></div>
                    </div>
                `;
                
                chatMessages.appendChild(typingDiv);
                chatMessages.scrollTop = chatMessages.scrollHeight;
            }
            
            function hideTypingIndicator() {
                isTyping = false;
                const typingMessage = document.getElementById('vmo-typing-message');
                if (typingMessage) {
                    typingMessage.remove();
                }
            }
            
            function handleSpecialAction(action, actionData) {
                switch (action) {
                    case 'open_contact_form':
                        // Open contact form if available
                        break;
                    case 'show_business_hours':
                        addMessage('Our business hours are: <?php echo esc_js($settings['business_hours']); ?>', 'ai');
                        break;
                    case 'capture_lead':
                        // Handle lead capture
                        break;
                }
            }
            
            // Show notification initially
            setTimeout(function() {
                if (!isOpen) {
                    chatNotification.style.display = 'flex';
                }
            }, 5000);
        });
        </script>
        
        <?php
    }
    
    /**
     * Process chat messages from website visitors
     */
    public function process_website_chat() {
        // Phone system webhook gateway (served via the already-allowlisted action `vmo_website_chat`).
        // Some edge/WAF setups block custom `admin-ajax.php?action=...` values (e.g., ones containing
        // "twilio"). This gateway avoids those blocked action names while still reaching WordPress.
        
        // CRITICAL: Clean any lingering output buffers from WordPress initialization BEFORE
        // we detect what kind of request this is. If output buffers are left open, wp_send_json_*
        // calls inside ajax handlers will not work properly.
        while (ob_get_level() > 0) {
            @ob_end_clean();
        }
        
        $vmo_gw = sanitize_key((string) ($_REQUEST['vmo_gw'] ?? ''));
        $kind = sanitize_key((string) ($_REQUEST['kind'] ?? ''));
        $has_key_param = isset($_REQUEST['k']) && is_string($_REQUEST['k']) && $_REQUEST['k'] !== '';

        $is_pd_dashboard_kind = in_array($kind, array('pd_campaigns', 'pd_live_calls', 'pd_takeover'), true);
        $is_sd_dashboard_kind = in_array($kind, array('sd_ajax'), true);

        // Some layers strip specific query params; allow gateway detection via `kind`/`k` too.
        // Dashboard proxy kinds are authenticated via WP REST nonce (no shared secret).
        $is_phone_gateway_request = ($vmo_gw === 'phone') || ($kind === 'ping') || ($kind !== '' && $has_key_param);
        $is_dashboard_gateway_request = $is_pd_dashboard_kind || $is_sd_dashboard_kind;

        if ($is_phone_gateway_request || $is_dashboard_gateway_request) {
            $send_json = static function ($payload, int $status = 200): void {
                while (ob_get_level() > 0) {
                    @ob_end_clean();
                }
                if (function_exists('nocache_headers')) {
                    nocache_headers();
                }
                status_header($status);
                header('Content-Type: application/json; charset=UTF-8');
                echo wp_json_encode($payload);
                exit;
            };

            $send_rest_like = static function ($resp) use ($send_json): void {
                if ($resp instanceof WP_REST_Response) {
                    $send_json($resp->get_data(), (int) $resp->get_status());
                }
                if (is_wp_error($resp)) {
                    $status = 500;
                    $data = $resp->get_error_data();
                    if (is_array($data) && isset($data['status'])) {
                        $status = (int) $data['status'];
                    }
                    $send_json(array('success' => false, 'message' => $resp->get_error_message()), $status);
                }
                if (is_array($resp)) {
                    $send_json($resp, 200);
                }
                $send_json(array('success' => true), 200);
            };

            $verify_rest_nonce = static function (): bool {
                if (!function_exists('wp_verify_nonce')) {
                    return false;
                }

                if (!is_user_logged_in()) {
                    return false;
                }

                $nonce = '';
                if (!empty($_SERVER['HTTP_X_WP_NONCE'])) {
                    $nonce = (string) $_SERVER['HTTP_X_WP_NONCE'];
                } elseif (isset($_REQUEST['_wpnonce'])) {
                    $nonce = sanitize_text_field(wp_unslash($_REQUEST['_wpnonce']));
                } elseif (isset($_REQUEST['nonce'])) {
                    $nonce = sanitize_text_field(wp_unslash($_REQUEST['nonce']));
                } elseif (isset($_REQUEST['security'])) {
                    // Some dashboards reuse this field; accept for convenience.
                    $nonce = sanitize_text_field(wp_unslash($_REQUEST['security']));
                }

                $nonce = sanitize_text_field($nonce);
                if ($nonce === '') {
                    return false;
                }

                return (bool) wp_verify_nonce($nonce, 'wp_rest');
            };

            if ($kind === 'ping') {
                header('Content-Type: text/plain; charset=UTF-8');
                echo 'pong';
                exit;
            }

            // Authenticated Strategic Dashboard proxy for selected admin-ajax actions.
            // This avoids edge/WAF blocking on specific `action=` values by tunneling through
            // the allowlisted `vmo_website_chat` handler.
            if ($is_sd_dashboard_kind) {
                if (!is_user_logged_in()) {
                    error_log('[VMO Gateway] sd_ajax 403: user not logged in');
                    $send_json(array('success' => false, 'message' => 'Forbidden'), 403);
                }

                if (!function_exists('vmo_verify_admin_security')) {
                    error_log('[VMO Gateway] sd_ajax 403: vmo_verify_admin_security function not found');
                    $send_json(array('success' => false, 'message' => 'Security check failed'), 403);
                }

                if (!vmo_verify_admin_security()) {
                    // Log details to help diagnose nonce issues
                    $sec  = isset($_POST['security']) ? substr((string)$_POST['security'], 0, 10) . '…' : '(missing)';
                    $nc   = isset($_POST['nonce'])    ? substr((string)$_POST['nonce'], 0, 10) . '…'    : '(missing)';
                    $uid  = get_current_user_id();
                    $act  = isset($_REQUEST['ajax_action']) ? sanitize_key($_REQUEST['ajax_action']) : '(none)';
                    error_log("[VMO Gateway] sd_ajax 403: nonce failed — security={$sec} nonce={$nc} uid={$uid} ajax_action={$act}");
                    $send_json(array('success' => false, 'message' => 'Security check failed'), 403);
                }

                $ajax_action = sanitize_key((string) ($_REQUEST['ajax_action'] ?? ''));
                if ($ajax_action === '') {
                    $send_json(array('success' => false, 'message' => 'Missing ajax_action'), 400);
                }

                // Accept any vmo_* action through the gateway.
                // This prevents hosting WAF from blocking individual action names with 404s.
                if (strpos($ajax_action, 'vmo_') !== 0) {
                    $send_json(array('success' => false, 'message' => 'Unknown action'), 404);
                }

                // Execute the existing handler.
                // Most wp_ajax_* handlers end the request via wp_send_json_* (wp_die).
                while (ob_get_level() > 0) {
                    @ob_end_clean();
                }
                if (function_exists('nocache_headers')) {
                    nocache_headers();
                }

                // Some handlers (or core nonce helpers) can terminate with `wp_die()` which may
                // output HTML, `0`, or `-1`. That breaks dashboard JSON parsing.
                // Install a scoped `wp_die` handler that converts non-JSON deaths into JSON.
                $has_json_header = static function (): bool {
                    if (headers_sent()) {
                        // If headers are already sent, assume handler already printed JSON.
                        return true;
                    }
                    $headers = function_exists('headers_list') ? headers_list() : array();
                    foreach ($headers as $h) {
                        if (stripos($h, 'content-type:') !== false && stripos($h, 'application/json') !== false) {
                            return true;
                        }
                    }
                    return false;
                };

                add_filter('wp_die_handler', static function () use ($send_json, $has_json_header) {
                    return static function ($message = '', $title = '', $args = array()) use ($send_json, $has_json_header) {
                        // If the handler already sent JSON (e.g., via wp_send_json_*), don't
                        // output anything here; just terminate to prevent non-JSON tails.
                        if ($has_json_header()) {
                            exit;
                        }

                        $status = 500;
                        if (is_array($args) && isset($args['response'])) {
                            $status = (int) $args['response'];
                        }

                        $msg = '';
                        if (is_wp_error($message)) {
                            $msg = $message->get_error_message();
                        } elseif (is_string($message)) {
                            $msg = wp_strip_all_tags($message);
                        }

                        if ($msg === '' || $msg === '-1' || $msg === '0') {
                            $msg = 'Request failed';
                        }

                        $send_json(array('success' => false, 'message' => $msg), $status > 0 ? $status : 500);
                    };
                });

                // Execute the handler. Do NOT use ob_start() because wp_send_json_* functions
                // output JSON immediately and force header flush. Using output buffering would
                // prevent us from capturing that output in a catch block.
                // Instead, rely on the wp_die handler we installed above to catch any exceptions.
                try {
                    do_action('wp_ajax_' . $ajax_action);
                    // If handler returns without calling wp_die/wp_send_json_*, it's an error
                    $send_json(array('success' => false, 'message' => 'Handler did not respond'), 500);
                } catch (Exception $e) {
                    // If an exception occurred (e.g., WP_Die_Exception from wp_send_json_*),
                    // check if JSON headers were already sent. If so, the handler output
                    // JSON directly and our wp_die handler will exit.
                    // If JSON headers weren't sent, our custom wp_die handler already sent error JSON.
                    exit;
                }
            }

            // Authenticated dashboard proxy (Power Dialer). Uses WP REST nonce for auth.
            if ($is_pd_dashboard_kind) {
                if (!class_exists('VMO_Twilio_Manager')) {
                    $send_json(array('success' => false, 'message' => 'Twilio manager unavailable'), 500);
                }

                if (!$verify_rest_nonce()) {
                    $send_json(array('success' => false, 'message' => 'Forbidden'), 403);
                }

                if (!class_exists('WP_REST_Request')) {
                    $send_json(array('success' => false, 'message' => 'REST request class unavailable'), 500);
                }

                $method = isset($_SERVER['REQUEST_METHOD']) ? strtoupper((string) $_SERVER['REQUEST_METHOD']) : 'GET';
                $route = '/vmo/v1/power-dialer/live-calls';
                if ($kind === 'pd_campaigns') {
                    $route = '/vmo/v1/power-dialer/campaigns';
                } elseif ($kind === 'pd_takeover') {
                    $route = '/vmo/v1/power-dialer/takeover';
                }

                $req = new WP_REST_Request($method, $route);
                $req->set_query_params(wp_unslash($_GET));

                // Capture JSON body for POST/PUT requests (admin-ajax doesn't populate $_POST for JSON).
                // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents -- reading php://input to populate a manually-constructed WP_REST_Request; no WP_Filesystem equivalent.
                $raw = file_get_contents('php://input');
                if (is_string($raw) && $raw !== '') {
                    $req->set_body($raw);
                    if (method_exists($req, 'set_header')) {
                        $req->set_header('content-type', 'application/json');
                    }
                }

                $req->set_param('vmo_source', 'ajax_gateway');

                $manager = VMO_Twilio_Manager::get_instance();
                try {
                    if ($kind === 'pd_campaigns') {
                        $send_rest_like($manager->power_dialer_campaigns($req));
                    }
                    if ($kind === 'pd_live_calls') {
                        $send_rest_like($manager->power_dialer_live_calls($req));
                    }
                    if ($kind === 'pd_takeover') {
                        $send_rest_like($manager->power_dialer_user_takeover($req));
                    }

                    $send_json(array('success' => false, 'message' => 'Unknown kind'), 404);
                } catch (Throwable $e) {
                    $send_json(array('success' => false, 'message' => 'Endpoint error'), 500);
                }
            }

            // Require a shared secret so this endpoint can't be abused.
            if (!class_exists('VMO_Twilio_Manager')) {
                status_header(500);
                header('Content-Type: text/plain; charset=UTF-8');
                echo 'Twilio manager unavailable';
                exit;
            }

            $key = sanitize_text_field(wp_unslash($_REQUEST['k'] ?? ''));
            $stored_key = (string) get_option('vmo_phone_webhook_key', '');
            if ($stored_key === '') {
                $stored_key = wp_generate_password(32, false, false);
                update_option('vmo_phone_webhook_key', $stored_key, true);
            }
            if ($key === '' || !hash_equals($stored_key, $key)) {
                status_header(403);
                header('Content-Type: text/plain; charset=UTF-8');
                echo 'Forbidden';
                exit;
            }
            if ($kind === '') {
                status_header(400);
                header('Content-Type: text/plain; charset=UTF-8');
                echo 'Missing kind';
                exit;
            }

            // Minimal REST-like request wrapper.
            $params = wp_unslash($_REQUEST);
                $body = file_get_contents('php://input');
                if (!is_string($body)) {
                    $body = '';
                }
                $raw_headers = function_exists('getallheaders') ? getallheaders() : array();
                if (!is_array($raw_headers) || empty($raw_headers)) {
                    $raw_headers = array();
                    foreach ($_SERVER as $server_key => $server_value) {
                        if (strpos($server_key, 'HTTP_') !== 0) {
                            continue;
                        }
                        $header_name = str_replace('_', '-', strtolower(substr($server_key, 5)));
                        $raw_headers[$header_name] = $server_value;
                    }
                }
                $normalized_headers = array();
                foreach ($raw_headers as $header_name => $header_value) {
                    $normalized_headers[str_replace('-', '_', strtolower((string) $header_name))] = array((string) $header_value);
                }
                $request = new class($params, $body, $normalized_headers) {
                    private array $params;
                    private string $body;
                    private array $headers;
                    public function __construct(array $params, string $body, array $headers) {
                        $this->params = $params;
                        $this->body = $body;
                        $this->headers = $headers;
                    }
                    public function get_params(): array { return $this->params; }
                    public function get_json_params(): array { return array(); }
                    public function get_body(): string { return $this->body; }
                    public function get_headers(): array { return $this->headers; }
            };

            if (function_exists('nocache_headers')) {
                nocache_headers();
            }

            $manager = VMO_Twilio_Manager::get_instance();

            // Log phone gateway requests for diagnostics
            $gw_start = microtime(true);
            error_log('[VMO Phone Gateway] kind=' . $kind . ' from=' . ($_SERVER['REMOTE_ADDR'] ?? 'unknown'));

            try {
                switch ($kind) {
                    case 'voice':
                        $manager->handle_voice_webhook($request);
                        error_log('[VMO Phone Gateway] voice completed in ' . round((microtime(true) - $gw_start) * 1000) . 'ms');
                        exit;

                    case 'ai_converse':
                        $manager->handle_ai_conversation($request);
                        exit;

                    case 'ai_converse_whisper':
                        $manager->handle_ai_conversation_whisper($request);
                        exit;

                    case 'pd_ai_converse':
                        $manager->handle_pd_ai_conversation($request);
                        exit;

                    case 'browser_call':
                        $manager->handle_browser_call($request);
                        exit;

                    case 'pd_twiml':
                    case 'power_dialer_twiml':
                        $manager->power_dialer_twiml($request);
                        exit;

                    case 'status':
                    case 'status_callback':
                        ob_start();
                        $resp = $manager->handle_status_callback($request);
                        header('Content-Type: application/json; charset=UTF-8');
                        if ($resp instanceof WP_REST_Response) {
                            status_header($resp->get_status());
                            echo wp_json_encode($resp->get_data());
                        } elseif (is_wp_error($resp)) {
                            status_header(500);
                            echo wp_json_encode(array('success' => false, 'message' => $resp->get_error_message()));
                        } else {
                            status_header(200);
                            echo wp_json_encode(is_array($resp) ? $resp : array('success' => true));
                        }
                        // Flush response so post-response work runs after client disconnects
                        if (!headers_sent()) { header('Connection: close'); }
                        $sz = ob_get_length(); if ($sz !== false && !headers_sent()) { header('Content-Length: ' . $sz); }
                        while (ob_get_level()) { ob_end_flush(); } flush();
                        if (function_exists('fastcgi_finish_request')) { fastcgi_finish_request(); }
                        elseif (function_exists('litespeed_finish_request')) { litespeed_finish_request(); }
                        ignore_user_abort(true);
                        if (function_exists('set_time_limit')) { set_time_limit(120); }
                        // Post-response: run summary + email pipeline directly (no cron dependency)
                        $gw_call_sid = sanitize_text_field(wp_unslash($_REQUEST['CallSid'] ?? ''));
                        $gw_call_status = sanitize_text_field(wp_unslash($_REQUEST['CallStatus'] ?? ''));
                        $gw_recording = esc_url_raw(wp_unslash($_REQUEST['RecordingUrl'] ?? ''));
                        if ($gw_call_sid !== '' && $gw_call_status === 'completed') {
                            try {
                                if (!empty($gw_recording)) {
                                    error_log('[VMO GW Status] Post-response: generating summary for ' . $gw_call_sid);
                                    $manager->generate_call_summary($gw_call_sid, $gw_recording);
                                }
                                error_log('[VMO GW Status] Post-response: sending email for ' . $gw_call_sid);
                                $manager->send_post_call_summary_email($gw_call_sid);
                            } catch (\Throwable $e) {
                                error_log('[VMO GW Status] Post-response pipeline failed: ' . $e->getMessage());
                            }
                        }
                        exit;

                    case 'sms':
                    case 'sms_webhook':
                        $resp = $manager->handle_sms_webhook($request);
                        header('Content-Type: application/json; charset=UTF-8');
                        if ($resp instanceof WP_REST_Response) {
                            status_header($resp->get_status());
                            echo wp_json_encode($resp->get_data());
                        } else {
                            status_header(200);
                            echo wp_json_encode(array('success' => true));
                        }
                        exit;

                    case 'dial_status':
                        $resp = $manager->handle_dial_status($request);
                        header('Content-Type: application/json; charset=UTF-8');
                        if ($resp instanceof WP_REST_Response) {
                            status_header($resp->get_status());
                            echo wp_json_encode($resp->get_data());
                        } else {
                            status_header(200);
                            echo wp_json_encode(array('success' => true));
                        }
                        exit;

                    case 'transcription':
                        $resp = $manager->handle_transcription_callback($request);
                        header('Content-Type: application/json; charset=UTF-8');
                        if ($resp instanceof WP_REST_Response) {
                            status_header($resp->get_status());
                            echo wp_json_encode($resp->get_data());
                        } else {
                            status_header(200);
                            echo wp_json_encode(array('success' => true));
                        }
                        exit;

                    case 'recording':
                        ob_start();
                        $resp = $manager->handle_recording_callback($request);
                        header('Content-Type: application/json; charset=UTF-8');
                        status_header(200);
                        echo wp_json_encode(is_array($resp) ? $resp : array('ok' => true));
                        // Flush response so post-response work runs after client disconnects
                        if (!headers_sent()) { header('Connection: close'); }
                        $sz = ob_get_length(); if ($sz !== false && !headers_sent()) { header('Content-Length: ' . $sz); }
                        while (ob_get_level()) { ob_end_flush(); } flush();
                        if (function_exists('fastcgi_finish_request')) { fastcgi_finish_request(); }
                        elseif (function_exists('litespeed_finish_request')) { litespeed_finish_request(); }
                        ignore_user_abort(true);
                        if (function_exists('set_time_limit')) { set_time_limit(120); }
                        // Post-response: run summary + email pipeline directly (no cron dependency)
                        // The handler already registered shutdown functions, but these explicit
                        // calls serve as a belt-and-suspenders fallback.
                        $gw_rec_call_sid = sanitize_text_field(wp_unslash($_REQUEST['CallSid'] ?? ''));
                        $gw_rec_url = esc_url_raw(wp_unslash($_REQUEST['RecordingUrl'] ?? ''));
                        $gw_rec_status = sanitize_text_field(wp_unslash($_REQUEST['RecordingStatus'] ?? ''));
                        if ($gw_rec_call_sid !== '' && !empty($gw_rec_url) && ($gw_rec_status === '' || $gw_rec_status === 'completed')) {
                            try {
                                error_log('[VMO GW Recording] Post-response: generating summary for ' . $gw_rec_call_sid);
                                $manager->generate_call_summary($gw_rec_call_sid, $gw_rec_url);
                                error_log('[VMO GW Recording] Post-response: sending email for ' . $gw_rec_call_sid);
                                $manager->send_post_call_summary_email($gw_rec_call_sid);
                            } catch (\Throwable $e) {
                                error_log('[VMO GW Recording] Post-response pipeline failed: ' . $e->getMessage());
                            }
                        }
                        exit;

                    case 'pd_outbound':
                    case 'pd_outbound_callback':
                        $resp = $manager->power_dialer_outbound_callback($request);
                        header('Content-Type: application/json; charset=UTF-8');
                        if ($resp instanceof WP_REST_Response) {
                            status_header($resp->get_status());
                            echo wp_json_encode($resp->get_data());
                        } else {
                            status_header(200);
                            echo wp_json_encode(is_array($resp) ? $resp : array('success' => true));
                        }
                        exit;

                    case 'ext_ring':
                        $manager->handle_ext_ring($request);
                        exit;

                    case 'realtime_dial_status':
                        $manager->handle_realtime_dial_status($request);
                        exit;

                    case 'realtime_participant_status':
                        $resp = $manager->handle_realtime_participant_status($request);
                        header('Content-Type: application/json; charset=UTF-8');
                        if ($resp instanceof WP_REST_Response) {
                            status_header($resp->get_status());
                            echo wp_json_encode($resp->get_data());
                        } elseif (is_wp_error($resp)) {
                            status_header(500);
                            echo wp_json_encode(array('success' => false, 'message' => $resp->get_error_message()));
                        } else {
                            status_header(200);
                            echo wp_json_encode(is_array($resp) ? $resp : array('success' => true));
                        }
                        exit;

                    case 'realtime_transfer_twiml':
                        $manager->handle_realtime_transfer_twiml($request);
                        exit;

                    case 'premium_extension_ring':
                        $resp = $manager->handle_premium_extension_ring($request);
                        header('Content-Type: application/json; charset=UTF-8');
                        if ($resp instanceof WP_REST_Response) {
                            status_header($resp->get_status());
                            echo wp_json_encode($resp->get_data());
                        } elseif (is_wp_error($resp)) {
                            $data = $resp->get_error_data();
                            status_header(is_array($data) && isset($data['status']) ? (int) $data['status'] : 500);
                            echo wp_json_encode(array('success' => false, 'message' => $resp->get_error_message()));
                        } else {
                            status_header(200);
                            echo wp_json_encode(is_array($resp) ? $resp : array('success' => true));
                        }
                        exit;

                    case 'openai_realtime_webhook':
                        $resp = $manager->handle_openai_realtime_webhook($request);
                        header('Content-Type: application/json; charset=UTF-8');
                        if ($resp instanceof WP_REST_Response) {
                            status_header($resp->get_status());
                            echo wp_json_encode($resp->get_data());
                        } elseif (is_wp_error($resp)) {
                            status_header(500);
                            echo wp_json_encode(array('success' => false, 'message' => $resp->get_error_message()));
                        } else {
                            status_header(200);
                            echo wp_json_encode(is_array($resp) ? $resp : array('success' => true));
                        }
                        exit;

                    case 'ext_listen_action':
                        $manager->handle_ext_listen_action($request);
                        exit;

                    case 'ext_monitor':
                        $manager->handle_ext_monitor($request);
                        exit;

                    default:
                        status_header(404);
                        header('Content-Type: text/plain; charset=UTF-8');
                        echo 'Unknown kind';
                        exit;
                }
            } catch (Throwable $e) {
                error_log('[VMO Phone Gateway] kind=' . $kind . ' failed: ' . $e->getMessage());
                if (in_array($kind, array('ext_ring', 'ext_listen_action', 'ext_monitor'), true)) {
                    status_header(200);
                    header('Content-Type: text/xml; charset=UTF-8');
                    echo '<?xml version="1.0" encoding="UTF-8"?>';
                    echo '<Response><Say>We could not connect the call menu. The A I will continue handling the call. Goodbye.</Say><Hangup/></Response>';
                    exit;
                }
                status_header(500);
                header('Content-Type: text/plain; charset=UTF-8');
                echo 'Endpoint error';
                exit;
            }
        }

        $message = sanitize_text_field($_POST['message'] ?? '');
        $business_context = json_decode(wp_unslash($_POST['business_context'] ?? '{}'), true);
        
        if (empty($message)) {
            wp_send_json_error(array('message' => 'No message provided'));
        }
        
        // ✅ TOKEN DEDUCTION v8.1.0: Charge the WEBSITE OWNER for visitor chat (150 tokens per message)
        // Get the site owner (not the visitor) - they pay for their customers' AI usage
        $site_owner_id = get_option('vmo_website_owner_id', 0);
        if (!$site_owner_id) {
            // Fallback to admin user
            $admins = get_users(array('role' => 'administrator', 'number' => 1));
            $site_owner_id = !empty($admins) ? $admins[0]->ID : 0;
        }
        
        if ($site_owner_id && function_exists('vmo_deduct_tokens')) {
            $token_cost = function_exists('vmo_get_token_cost') ? (int) vmo_get_token_cost('website_chat') : 150;
            if (!vmo_deduct_tokens($site_owner_id, $token_cost, 'website_chat', 'Visitor AI chat message')) {
                wp_send_json_error(array(
                    'message' => "I'm currently unavailable. Please contact us directly for assistance.",
                    'status' => 'chat_unavailable'
                ));
                return;
            }
        }
        
        // Get website content for context
        $website_context = $this->get_website_context();
        
        // Generate AI response
        $ai_response = $this->generate_ai_response($message, $business_context, $website_context);
        
        // Check for special actions
        $action_data = $this->check_for_special_actions($message, $ai_response);
        
        wp_send_json_success(array(
            'response' => $ai_response,
            'action' => $action_data['action'] ?? null,
            'actionData' => $action_data['data'] ?? null
        ));
    }
    
    /**
     * Get website content for AI context
     */
    private function get_website_context() {
        $context = array();
        
        // Get recent posts/pages
        $recent_content = get_posts(array(
            'numberposts' => 5,
            'post_type' => array('post', 'page'),
            'post_status' => 'publish'
        ));
        
        $context['recent_content'] = array();
        foreach ($recent_content as $post) {
            $context['recent_content'][] = array(
                'title' => $post->post_title,
                'excerpt' => wp_trim_words($post->post_content, 50),
                'url' => get_permalink($post->ID)
            );
        }
        
        // Get menu items
        $menu_locations = get_nav_menu_locations();
        if (!empty($menu_locations)) {
            $menu_items = wp_get_nav_menu_items(array_values($menu_locations)[0]);
            $context['navigation'] = array();
            foreach ($menu_items as $item) {
                $context['navigation'][] = array(
                    'title' => $item->title,
                    'url' => $item->url
                );
            }
        }
        
        // Get business settings
        $context['business_info'] = $this->assistant_settings;
        
        return $context;
    }
    
    /**
     * Generate AI response using OpenAI
     */
    private function generate_ai_response($user_message, $business_context, $website_context) {
        if (empty($this->api_key)) {
            return "I'm currently unable to process your request. Please contact us directly for assistance.";
        }
        
        // ✅ TOKEN DEDUCTION v8.1.0: Charge for website AI assistant response
        $user_id = get_current_user_id();
        if (function_exists('vmo_deduct_tokens')) {
            $token_cost = function_exists('vmo_get_token_cost') ? (int) vmo_get_token_cost('website_chat') : 150;
            if (!vmo_deduct_tokens($user_id, $token_cost, 'website_chat', 'Website AI assistant response')) {
                return "Your available VMO Credit has been used up. Please add a booster or upgrade to a higher-credit plan to continue metered AI assistant responses.";
            }
        }
        
        $system_prompt = $this->build_system_prompt($business_context, $website_context);
        
        // ✅ FIX: Use centralized model registry
        $_wa_model = function_exists('vmo_get_model') ? vmo_get_model('fast') : (defined('VMO_OPENAI_MODEL') ? VMO_OPENAI_MODEL : 'gpt-5.5-mini');
        $data = array_merge(array(
            'model' => $_wa_model,
            'messages' => array(
                array(
                    'role' => 'system',
                    'content' => $system_prompt
                ),
                array(
                    'role' => 'user',
                    'content' => $user_message
                )
            ),
            'temperature' => 0.7
        ), function_exists('vmo_get_token_param') ? vmo_get_token_param($_wa_model, 500) : array('max_tokens' => 500));
        
        $args = array(
            'headers' => array(
                'Authorization' => 'Bearer ' . $this->api_key,
                'Content-Type' => 'application/json',
            ),
            'body' => json_encode($data),
            'method' => 'POST',
            'timeout' => 30
        );
        
        $response = wp_remote_post('https://api.openai.com/v1/chat/completions', $args);

        // Fallback Logic
        if (is_wp_error($response) || wp_remote_retrieve_response_code($response) >= 400) {
            $data['model'] = function_exists('vmo_get_model') ? vmo_get_model('fallback') : 'gpt-5.5-nano';
            $args['body'] = json_encode($data);
            $response = wp_remote_post('https://api.openai.com/v1/chat/completions', $args);
        }
        
        if (is_wp_error($response)) {
            return "I'm currently experiencing technical difficulties. Please try again later or contact us directly.";
        }
        
        $body = wp_remote_retrieve_body($response);
        $result = json_decode($body, true);
        
        if (isset($result['choices'][0]['message']['content'])) {
            return trim($result['choices'][0]['message']['content']);
        }
        
        return "I'm having trouble responding right now. Please contact us directly for immediate assistance.";
    }
    
    /**
     * Build system prompt for AI assistant
     */
    private function build_system_prompt($business_context, $website_context) {
        $settings = $this->assistant_settings;
        
        $prompt = "You are a helpful AI assistant for {$settings['business_name']}. ";
        
        if (!empty($settings['business_description'])) {
            $prompt .= "Business description: {$settings['business_description']}. ";
        }
        
        $prompt .= "\nYou can help visitors with:\n";
        
        if ($settings['enabled_features']['general_inquiries']) {
            $prompt .= "- General questions about the business and services\n";
        }
        if ($settings['enabled_features']['appointment_booking']) {
            $prompt .= "- Appointment booking and scheduling\n";
        }
        if ($settings['enabled_features']['product_support']) {
            $prompt .= "- Product information and support\n";
        }
        if ($settings['enabled_features']['sales_assistance']) {
            $prompt .= "- Sales inquiries and pricing information\n";
        }
        if ($settings['enabled_features']['lead_capture']) {
            $prompt .= "- Connecting visitors with the business team\n";
        }
        
        $prompt .= "\nBusiness Information:\n";
        $prompt .= "- Business Hours: {$settings['business_hours']}\n";
        
        if (!empty($settings['contact_info']['phone'])) {
            $prompt .= "- Phone: {$settings['contact_info']['phone']}\n";
        }
        if (!empty($settings['contact_info']['email'])) {
            $prompt .= "- Email: {$settings['contact_info']['email']}\n";
        }
        if (!empty($settings['contact_info']['address'])) {
            $prompt .= "- Address: {$settings['contact_info']['address']}\n";
        }
        
        // Add website context
        if (!empty($website_context['recent_content'])) {
            $prompt .= "\nRecent website content includes:\n";
            foreach (array_slice($website_context['recent_content'], 0, 3) as $content) {
                $prompt .= "- {$content['title']}: {$content['excerpt']}\n";
            }
        }
        
        $prompt .= "\nGuidelines:\n";
        $prompt .= "- Be helpful, friendly, and professional\n";
        $prompt .= "- Keep responses concise but informative\n";
        $prompt .= "- If you can't answer something, direct them to contact the business directly\n";
        $prompt .= "- Always stay in character as a representative of this specific business\n";
        $prompt .= "- Use natural, conversational language\n";
        $prompt .= "- Format responses with proper line breaks for readability\n";
        
        return $prompt;
    }
    
    /**
     * Check for special actions in the conversation
     */
    private function check_for_special_actions($user_message, $ai_response) {
        $message_lower = strtolower($user_message);
        $actions = array();
        
        // Check for common action triggers
        if (strpos($message_lower, 'business hours') !== false || strpos($message_lower, 'hours') !== false) {
            $actions['action'] = 'show_business_hours';
        }
        
        if (strpos($message_lower, 'contact') !== false || strpos($message_lower, 'reach') !== false) {
            $actions['action'] = 'open_contact_form';
        }
        
        if (strpos($message_lower, 'appointment') !== false || strpos($message_lower, 'book') !== false || strpos($message_lower, 'schedule') !== false) {
            $actions['action'] = 'capture_lead';
            $actions['data'] = array('type' => 'appointment');
        }
        
        return $actions;
    }
}

// Initialize the AI Website Assistant
new VMO_Website_AI_Assistant();
