<?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.
        $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);
                    };
                });

                // Capture any accidental output; if the handler returns without dying, we'll
                // respond with JSON ourselves.
                @ob_start();
                do_action('wp_ajax_' . $ajax_action);
                $out = (string) @ob_get_clean();
                if ($out !== '') {
                    $out = trim(preg_replace('/\s+/', ' ', $out));
                    $out = substr($out, 0, 250);
                    $send_json(array('success' => false, 'message' => 'Handler returned unexpected output', 'data' => array('preview' => $out)), 500);
                }

                // If handler did not terminate or output anything, return a generic error.
                $send_json(array('success' => false, 'message' => 'Handler did not respond'), 500);
            }

            // 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);
            $request = new class($params) {
                private array $params;
                public function __construct(array $params) { $this->params = $params; }
                public function get_params(): array { return $this->params; }
                public function get_json_params(): array { return array(); }
            };

            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':
                        $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));
                        }
                        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':
                        $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));
                        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 '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) {
                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')) {
            if (!vmo_deduct_tokens($site_owner_id, 150, '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')) {
            if (!vmo_deduct_tokens($user_id, 150, 'chat', 'Website AI assistant response')) {
                return "Your subscription credit has run out. Please top up to continue using the AI assistant.";
            }
        }
        
        $system_prompt = $this->build_system_prompt($business_context, $website_context);
        
        // ✅ FIX: GPT-5.2 requires max_completion_tokens, not max_tokens
        $_wa_model = 'gpt-5.2-2025-12-11';
        $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'] = 'gpt-4o';
            // ✅ FIX: Swap max_completion_tokens back to max_tokens for gpt-4o
            if (isset($data['max_completion_tokens'])) {
                $data['max_tokens'] = $data['max_completion_tokens'];
                unset($data['max_completion_tokens']);
            }
            $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();
