<?php
session_start();
header('Content-Type: application/json');

require_once '../layouts/dbconn.php';

/**
 * AI Chatbot Response Handler
 * Processes user messages and generates AI responses
 */

try {
    $input = json_decode(file_get_contents('php://input'), true);
    
    $message = $input['message'] ?? '';
    $session_id = $input['session_id'] ?? '';
    $conversation_history = $input['conversation_history'] ?? [];
    
    if (empty($message)) {
        throw new Exception('Message is required');
    }
    
    // Get chatbot settings
    $settings_sql = "SELECT setting_key, setting_value FROM system_settings WHERE category = 'chatbot'";
    $settings_result = $conn->query($settings_sql);
    $settings = [];
    while ($row = $settings_result->fetch_assoc()) {
        $settings[$row['setting_key']] = $row['setting_value'];
    }
    
    if (!isset($settings['chatbot_enabled']) || $settings['chatbot_enabled'] != '1') {
        throw new Exception('Chatbot is not enabled');
    }
    
    $provider = $settings['chatbot_provider'] ?? 'openai';
    $api_key = $settings['chatbot_api_key'] ?? '';
    $model = $settings['chatbot_model'] ?? 'gpt-4';
    $temperature = floatval($settings['chatbot_temperature'] ?? 0.7);
    $max_tokens = intval($settings['chatbot_max_tokens'] ?? 500);
    $system_prompt = $settings['chatbot_system_prompt'] ?? 'You are an AI assistant for an ENT hospital.';
    
    if (empty($api_key)) {
        throw new Exception('Chatbot API key not configured');
    }
    
    // Prepare messages array
    $messages = [
        ['role' => 'system', 'content' => $system_prompt]
    ];
    
    // Add conversation history (keep last 10 messages)
    $history_limit = intval($settings['chatbot_history_length'] ?? 10);
    $recent_history = array_slice($conversation_history, -$history_limit);
    $messages = array_merge($messages, $recent_history);
    
    // Add current message
    $messages[] = ['role' => 'user', 'content' => $message];
    
    $start_time = microtime(true);
    
    // Get AI response based on provider
    if ($provider === 'openai') {
        $response_text = getOpenAIResponse($api_key, $model, $messages, $temperature, $max_tokens);
    } elseif ($provider === 'anthropic') {
        $response_text = getAnthropicResponse($api_key, $model, $messages, $temperature, $max_tokens, $system_prompt);
    } else {
        throw new Exception('Unsupported AI provider');
    }
    
    $response_time = round((microtime(true) - $start_time), 2);
    
    // Save conversation to database
    $user_id = $_SESSION['user_id'] ?? null;
    $save_sql = "INSERT INTO chatbot_conversations (user_id, user_session, user_message, bot_response, response_time, created_at) 
                VALUES (?, ?, ?, ?, ?, NOW())";
    $stmt = $conn->prepare($save_sql);
    $stmt->bind_param("isssd", $user_id, $session_id, $message, $response_text, $response_time);
    $stmt->execute();
    
    echo json_encode([
        'success' => true,
        'response' => $response_text,
        'response_time' => $response_time
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}

function getOpenAIResponse($api_key, $model, $messages, $temperature, $max_tokens) {
    $api_url = 'https://api.openai.com/v1/chat/completions';
    
    $data = [
        'model' => $model,
        'messages' => $messages,
        'temperature' => $temperature,
        'max_tokens' => $max_tokens
    ];
    
    $curl = curl_init();
    curl_setopt_array($curl, [
        CURLOPT_URL => $api_url,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => json_encode($data),
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => [
            'Authorization: Bearer ' . $api_key,
            'Content-Type: application/json'
        ],
        CURLOPT_SSL_VERIFYPEER => true,
        CURLOPT_TIMEOUT => 30
    ]);
    
    $response = curl_exec($curl);
    $http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    curl_close($curl);
    
    $result = json_decode($response, true);
    
    if ($http_code === 200 && isset($result['choices'][0]['message']['content'])) {
        return $result['choices'][0]['message']['content'];
    } else {
        $error_msg = $result['error']['message'] ?? 'Unknown OpenAI error';
        throw new Exception('OpenAI API error: ' . $error_msg);
    }
}

function getAnthropicResponse($api_key, $model, $messages, $temperature, $max_tokens, $system_prompt) {
    $api_url = 'https://api.anthropic.com/v1/messages';
    
    // Remove system message from messages array for Anthropic
    $user_messages = array_filter($messages, function($msg) {
        return $msg['role'] !== 'system';
    });
    
    $data = [
        'model' => $model,
        'max_tokens' => $max_tokens,
        'temperature' => $temperature,
        'system' => $system_prompt,
        'messages' => array_values($user_messages)
    ];
    
    $curl = curl_init();
    curl_setopt_array($curl, [
        CURLOPT_URL => $api_url,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => json_encode($data),
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => [
            'x-api-key: ' . $api_key,
            'anthropic-version: 2023-06-01',
            'Content-Type: application/json'
        ],
        CURLOPT_SSL_VERIFYPEER => true,
        CURLOPT_TIMEOUT => 30
    ]);
    
    $response = curl_exec($curl);
    $http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    curl_close($curl);
    
    $result = json_decode($response, true);
    
    if ($http_code === 200 && isset($result['content'][0]['text'])) {
        return $result['content'][0]['text'];
    } else {
        $error_msg = $result['error']['message'] ?? 'Unknown Anthropic error';
        throw new Exception('Anthropic API error: ' . $error_msg);
    }
}
?>