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

/**
 * VMO AI Website Builder - Conversation Manager
 * Handles conversation threads, message storage, and AI memory
 * Last modified: July 24, 2025
 */

if (!defined('ABSPATH')) exit;

class VMO_Conversation_Manager {
    
    private $current_conversation_id = null;
    private $context_window_size = 10; // Last 10 messages for context
    
    public function __construct() {
        add_action('wp_ajax_vmo_start_conversation', array($this, 'start_conversation'));
        add_action('wp_ajax_vmo_send_message', array($this, 'send_message'));
        add_action('wp_ajax_vmo_get_conversations', array($this, 'get_conversations'));
        add_action('wp_ajax_vmo_load_conversation', array($this, 'load_conversation'));
        add_action('wp_ajax_vmo_delete_conversation', array($this, 'delete_conversation'));
        add_action('wp_ajax_vmo_save_voice_recording', array($this, 'save_voice_recording'));
    }
    
    /**
     * Start a new conversation thread
     */
    public function start_conversation() {
        // Verify nonce
        if (!wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['security'])), 'vmo_builder_nonce')) {
            wp_send_json_error(array('message' => 'Security check failed'));
            return;
        }
        
        if (!is_user_logged_in()) {
            wp_send_json_error(array('message' => 'User not logged in'));
            return;
        }
        
        global $wpdb;
        $user_id = get_current_user_id();
        $title = sanitize_text_field($_POST['title'] ?? 'New Website Project');
        $project_id = sanitize_text_field($_POST['project_id'] ?? '');
        $context = json_encode(wp_unslash($_POST['context'] ?? array()));
        
        $conversations_table = $wpdb->prefix . 'vmo_conversations';
        
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $result = $wpdb->insert(
            $conversations_table,
            array(
                'user_id' => $user_id,
                'thread_title' => $title,
                'project_id' => $project_id,
                'context_data' => $context,
                'created_at' => current_time('mysql'),
                'updated_at' => current_time('mysql')
            ),
            array('%d', '%s', '%s', '%s', '%s', '%s')
        );
        
        if ($result === false) {
            wp_send_json_error(array('message' => 'Failed to create conversation'));
            return;
        }
        
        $conversation_id = $wpdb->insert_id;
        $this->current_conversation_id = $conversation_id;
        
        // Add initial system message
        $this->add_message($conversation_id, 'system', 
            'You are VMO AI, an expert website builder assistant. Help the user create amazing websites. ' .
            'Remember their preferences and previous requests in this conversation.'
        );
        
        wp_send_json_success(array(
            'conversation_id' => $conversation_id,
            'title' => $title,
            'message' => 'New conversation started'
        ));
    }
    
    /**
     * Send a message in the conversation
     */
    public function send_message() {
        // Verify nonce
        if (!wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['security'])), 'vmo_builder_nonce')) {
            wp_send_json_error(array('message' => 'Security check failed'));
            return;
        }
        
        if (!is_user_logged_in()) {
            wp_send_json_error(array('message' => 'User not logged in'));
            return;
        }
        
        $conversation_id = intval($_POST['conversation_id']);
        $message = sanitize_textarea_field($_POST['message']);
        $metadata = json_encode(wp_unslash($_POST['metadata'] ?? array()));
        
        if (empty($message)) {
            wp_send_json_error(array('message' => 'Message cannot be empty'));
            return;
        }
        
        // Verify user owns this conversation
        if (!$this->verify_conversation_ownership($conversation_id)) {
            wp_send_json_error(array('message' => 'Access denied'));
            return;
        }
        
        // Add user message
        $user_message_id = $this->add_message($conversation_id, 'user', $message, $metadata);
        
        if (!$user_message_id) {
            wp_send_json_error(array('message' => 'Failed to save message'));
            return;
        }
        
        // Get conversation context for AI
        $context_messages = $this->get_conversation_context($conversation_id);
        
        // Send to OpenAI with context
        $ai_response = $this->send_to_openai($context_messages);
        
        if ($ai_response['success']) {
            // Save AI response
            $ai_message_id = $this->add_message(
                $conversation_id, 
                'assistant', 
                $ai_response['content'],
                json_encode(array('tokens_used' => $ai_response['tokens_used']))
            );
            
            // Update conversation timestamp
            $this->update_conversation_timestamp($conversation_id);
            
            wp_send_json_success(array(
                'user_message_id' => $user_message_id,
                'ai_message_id' => $ai_message_id,
                'ai_response' => $ai_response['content'],
                'tokens_used' => $ai_response['tokens_used'],
                'remaining_tokens' => $this->get_user_token_balance()
            ));
        } else {
            wp_send_json_error(array('message' => $ai_response['error']));
        }
    }
    
    /**
     * Get all conversations for current user
     */
    public function get_conversations() {
        if (!wp_verify_nonce(sanitize_text_field(wp_unslash($_GET['security'])), 'vmo_builder_nonce')) {
            wp_send_json_error(array('message' => 'Security check failed'));
            return;
        }
        
        if (!is_user_logged_in()) {
            wp_send_json_error(array('message' => 'User not logged in'));
            return;
        }
        
        global $wpdb;
        $user_id = get_current_user_id();
        $conversations_table = $wpdb->prefix . 'vmo_conversations';
        
        $conversations = $wpdb->get_results($wpdb->prepare("
            SELECT id, thread_title, project_id, created_at, updated_at,
                   (SELECT COUNT(*) FROM {$wpdb->prefix}vmo_conversation_messages 
                    WHERE conversation_id = c.id) as message_count
            FROM $conversations_table c
            WHERE user_id = %d
            ORDER BY updated_at DESC
            LIMIT 50
        ", $user_id), ARRAY_A);
        
        wp_send_json_success(array('conversations' => $conversations));
    }
    
    /**
     * Load a specific conversation with messages
     */
    public function load_conversation() {
        if (!wp_verify_nonce(sanitize_text_field(wp_unslash($_GET['security'])), 'vmo_builder_nonce')) {
            wp_send_json_error(array('message' => 'Security check failed'));
            return;
        }
        
        if (!is_user_logged_in()) {
            wp_send_json_error(array('message' => 'User not logged in'));
            return;
        }
        
        $conversation_id = intval($_GET['conversation_id']);
        
        if (!$this->verify_conversation_ownership($conversation_id)) {
            wp_send_json_error(array('message' => 'Access denied'));
            return;
        }
        
        global $wpdb;
        $conversations_table = $wpdb->prefix . 'vmo_conversations';
        $messages_table = $wpdb->prefix . 'vmo_conversation_messages';
        
        // Get conversation info
        $conversation = $wpdb->get_row($wpdb->prepare("
            SELECT * FROM $conversations_table WHERE id = %d
        ", $conversation_id), ARRAY_A);
        
        // Get messages
        $messages = $wpdb->get_results($wpdb->prepare("
            SELECT * FROM $messages_table 
            WHERE conversation_id = %d 
            ORDER BY created_at ASC
        ", $conversation_id), ARRAY_A);
        
        $this->current_conversation_id = $conversation_id;
        
        wp_send_json_success(array(
            'conversation' => $conversation,
            'messages' => $messages
        ));
    }
    
    /**
     * Delete a conversation
     */
    public function delete_conversation() {
        if (!wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['security'])), 'vmo_builder_nonce')) {
            wp_send_json_error(array('message' => 'Security check failed'));
            return;
        }
        
        if (!is_user_logged_in()) {
            wp_send_json_error(array('message' => 'User not logged in'));
            return;
        }
        
        $conversation_id = intval($_POST['conversation_id']);
        
        if (!$this->verify_conversation_ownership($conversation_id)) {
            wp_send_json_error(array('message' => 'Access denied'));
            return;
        }
        
        global $wpdb;
        $conversations_table = $wpdb->prefix . 'vmo_conversations';
        
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $result = $wpdb->delete($conversations_table, array('id' => $conversation_id), array('%d'));
        
        if ($result !== false) {
            wp_send_json_success(array('message' => 'Conversation deleted'));
        } else {
            wp_send_json_error(array('message' => 'Failed to delete conversation'));
        }
    }
    
    /**
     * Save voice recording data
     */
    public function save_voice_recording() {
        if (!wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['security'])), 'vmo_builder_nonce')) {
            wp_send_json_error(array('message' => 'Security check failed'));
            return;
        }
        
        if (!is_user_logged_in()) {
            wp_send_json_error(array('message' => 'User not logged in'));
            return;
        }
        
        global $wpdb;
        $user_id = get_current_user_id();
        $recordings_table = $wpdb->prefix . 'vmo_voice_recordings';
        
        $conversation_id = intval($_POST['conversation_id'] ?? 0);
        $transcript = sanitize_textarea_field($_POST['transcript'] ?? '');
        $confidence = floatval($_POST['confidence'] ?? 0);
        $method = sanitize_text_field($_POST['method'] ?? 'whisper');
        $duration = floatval($_POST['duration'] ?? 0);
        $file_size = intval($_POST['file_size'] ?? 0);
        
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $result = $wpdb->insert(
            $recordings_table,
            array(
                'user_id' => $user_id,
                'conversation_id' => $conversation_id > 0 ? $conversation_id : null,
                'transcript' => $transcript,
                'confidence_score' => $confidence,
                'processing_method' => $method,
                'duration_seconds' => $duration,
                'file_size_bytes' => $file_size,
                'created_at' => current_time('mysql')
            ),
            array('%d', '%d', '%s', '%f', '%s', '%f', '%d', '%s')
        );
        
        if ($result !== false) {
            wp_send_json_success(array('recording_id' => $wpdb->insert_id));
        } else {
            wp_send_json_error(array('message' => 'Failed to save recording'));
        }
    }
    
    /**
     * Private helper methods
     */
    private function add_message($conversation_id, $type, $content, $metadata = null) {
        global $wpdb;
        $messages_table = $wpdb->prefix . 'vmo_conversation_messages';
        
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $result = $wpdb->insert(
            $messages_table,
            array(
                'conversation_id' => $conversation_id,
                'message_type' => $type,
                'content' => $content,
                'metadata' => $metadata,
                'created_at' => current_time('mysql')
            ),
            array('%d', '%s', '%s', '%s', '%s')
        );
        
        return $result !== false ? $wpdb->insert_id : false;
    }
    
    private function verify_conversation_ownership($conversation_id) {
        global $wpdb;
        $conversations_table = $wpdb->prefix . 'vmo_conversations';
        $user_id = get_current_user_id();
        
        $count = $wpdb->get_var($wpdb->prepare("
            SELECT COUNT(*) FROM $conversations_table 
            WHERE id = %d AND user_id = %d
        ", $conversation_id, $user_id));
        
        return $count > 0;
    }
    
    private function get_conversation_context($conversation_id) {
        global $wpdb;
        $messages_table = $wpdb->prefix . 'vmo_conversation_messages';
        
        $messages = $wpdb->get_results($wpdb->prepare("
            SELECT message_type, content FROM $messages_table 
            WHERE conversation_id = %d 
            ORDER BY created_at DESC 
            LIMIT %d
        ", $conversation_id, $this->context_window_size), ARRAY_A);
        
        // Reverse to get chronological order
        return array_reverse($messages);
    }
    
    private function send_to_openai($context_messages) {
        $api_key = get_option('vmo_openai_api_key', '');
        
        if (empty($api_key)) {
            return array('success' => false, 'error' => 'OpenAI API key not configured');
        }
        
        // ✅ TOKEN DEDUCTION FIX: Use centralized operation charging once per call.
        $user_id = get_current_user_id();
        $chat_token_cost = function_exists('vmo_get_token_cost') ? max(1, intval(vmo_get_token_cost('chat'))) : 50;
        if (function_exists('vmo_deduct_tokens_for_operation')) {
            if (!vmo_deduct_tokens_for_operation($user_id, 'chat')) {
                return array('success' => false, 'error' => 'Insufficient tokens. Please top up your balance.');
            }
        } elseif (function_exists('vmo_deduct_tokens')) {
            if (!vmo_deduct_tokens($user_id, $chat_token_cost, 'chat', 'Conversation AI response')) {
                return array('success' => false, 'error' => 'Insufficient tokens. Please top up your balance.');
            }
        }
        
        // Prepare messages for OpenAI
        $openai_messages = array();
        foreach ($context_messages as $msg) {
            $openai_messages[] = array(
                'role' => $msg['message_type'] === 'user' ? 'user' : 
                         ($msg['message_type'] === 'assistant' ? 'assistant' : 'system'),
                'content' => $msg['content']
            );
        }
        
        // ✅ FIX: Use VMO_OPENAI_MODEL and correct token parameter for GPT-5.2
        $model = defined('VMO_OPENAI_MODEL') ? VMO_OPENAI_MODEL : 'gpt-5.2';
        $token_param = function_exists('vmo_get_token_param') 
            ? vmo_get_token_param($model, 2000) 
            : array('max_completion_tokens' => 2000);
        
        $payload = array_merge(array(
            'model' => $model,
            'messages' => $openai_messages,
            'temperature' => 0.7,
            'presence_penalty' => 0.1,
            'frequency_penalty' => 0.1
        ), $token_param);
        
        $response = wp_remote_post('https://api.openai.com/v1/chat/completions', array(
            'timeout' => 120, // Increased timeout to 2 minutes
            'sslverify' => true,
            'redirection' => 5,
            'httpversion' => '1.0',
            'blocking' => true,
            'headers' => array(
                'Authorization' => 'Bearer ' . $api_key,
                'Content-Type' => 'application/json'
            ),
            'body' => json_encode($payload)
        ));
        
        if (is_wp_error($response)) {
            $error_message = $response->get_error_message();
            error_log( 'VMO AI Builder - Conversation API Error: ' . $error_message );
            return array(
                'success' => false, 
                'error' => $error_message,
                'debug_info' => array(
                    'error_code' => $response->get_error_code(),
                    'operation' => 'conversation_ai',
                    'timestamp' => current_time('mysql')
                )
            );
        }
        
        // Check HTTP response code
        $response_code = wp_remote_retrieve_response_code( $response );
        if ( $response_code !== 200 ) {
            $response_body = wp_remote_retrieve_body( $response );
            error_log( 'VMO AI Builder - Conversation HTTP Error ' . $response_code . ': ' . $response_body );
            return array(
                'success' => false,
                'error' => 'OpenAI API returned error code: ' . $response_code,
                'debug_info' => array(
                    'http_code' => $response_code,
                    'response_body' => $response_body,
                    'operation' => 'conversation_ai',
                    'timestamp' => current_time('mysql')
                )
            );
        }
        
        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);
        
        if (!isset($data['choices'][0]['message']['content'])) {
            $error = isset($data['error']['message']) ? $data['error']['message'] : 'Unknown API error';
            return array('success' => false, 'error' => $error);
        }
        
        return array(
            'success' => true,
            'content' => $data['choices'][0]['message']['content'],
            'tokens_used' => $data['usage']['total_tokens'] ?? 0
        );
    }
    
    private function update_conversation_timestamp($conversation_id) {
        global $wpdb;
        $conversations_table = $wpdb->prefix . 'vmo_conversations';
        
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $wpdb->update(
            $conversations_table,
            array('updated_at' => current_time('mysql')),
            array('id' => $conversation_id),
            array('%s'),
            array('%d')
        );
    }
    
    private function deduct_user_tokens($tokens) {
        $user_id = get_current_user_id();
        $current_balance = (int)get_user_meta($user_id, 'vmo_token_balance', true);
        $new_balance = max(0, $current_balance - $tokens);
        update_user_meta($user_id, 'vmo_token_balance', $new_balance);
    }
    
    private function get_user_token_balance() {
        $user_id = get_current_user_id();
        return (int)get_user_meta($user_id, 'vmo_token_balance', true);
    }
    
    /**
     * Public API methods
     */
    public function get_current_conversation_id() {
        return $this->current_conversation_id;
    }
    
    public function set_current_conversation_id($conversation_id) {
        $this->current_conversation_id = $conversation_id;
    }
}

// Initialize the conversation manager
new VMO_Conversation_Manager();
