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

// Check authentication
if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

// Include database connection
include_once '../layouts/dbconn.php';

// Get API key and settings from database
function getSetting($conn, $key) {
    $sql = "SELECT setting_value FROM system_settings WHERE setting_key = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("s", $key);
    $stmt->execute();
    $result = $stmt->get_result();
    $row = $result->fetch_assoc();
    $stmt->close();
    return $row['setting_value'] ?? '';
}

// Get chatbot settings
$api_key = getSetting($conn, 'chatbot_api_key');
$provider = getSetting($conn, 'chatbot_provider');
$model = getSetting($conn, 'chatbot_model');
$chatbot_enabled = getSetting($conn, 'chatbot_enabled');

// Default model if not set
if (empty($model)) {
    $model = 'claude-sonnet-4-20250514';
}

// Check if chatbot is enabled and configured
if ($chatbot_enabled != '1') {
    echo json_encode([
        'success' => false, 
        'message' => 'AI Chatbot is disabled. Please enable it in System Settings.'
    ]);
    exit();
}

if (empty($api_key) || $api_key === 'your-api-key-here') {
    echo json_encode([
        'success' => false, 
        'message' => 'AI Assistant not configured. Please add your API key in System Settings > Chatbot.'
    ]);
    exit();
}

// Get request data
$input = json_decode(file_get_contents('php://input'), true);
$action = $input['action'] ?? '';
$data = $input['data'] ?? [];

// Call Anthropic API with better error handling
function callAnthropicAPI($prompt, $api_key, $model) {
    $ch = curl_init('https://api.anthropic.com/v1/messages');
    
    $payload = json_encode([
        'model' => $model,
        'max_tokens' => 1500,
        'messages' => [
            [
                'role' => 'user',
                'content' => $prompt
            ]
        ]
    ]);
    
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => $payload,
        CURLOPT_HTTPHEADER => [
            'Content-Type: application/json',
            'x-api-key: ' . $api_key,
            'anthropic-version: 2023-06-01'
        ],
        CURLOPT_TIMEOUT => 30,
        CURLOPT_SSL_VERIFYPEER => true
    ]);
    
    $response = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curl_error = curl_error($ch);
    curl_close($ch);
    
    if ($curl_error) {
        error_log("CURL Error: " . $curl_error);
        return ['error' => 'Connection error: ' . $curl_error];
    }
    
    if ($http_code !== 200) {
        error_log("API Error (Code $http_code): " . $response);
        $error_data = json_decode($response, true);
        $error_message = $error_data['error']['message'] ?? 'API request failed';
        return ['error' => "API Error ($http_code): $error_message"];
    }
    
    return json_decode($response, true);
}

switch ($action) {
    
    case 'analyze_symptoms':
        $chiefComplaint = $data['chief_complaint'] ?? '';
        $historyPresent = $data['history_present'] ?? '';
        $age = $data['age'] ?? '';
        $gender = $data['gender'] ?? '';
        
        $prompt = "As an ENT specialist, analyze this case:

Chief Complaint: {$chiefComplaint}
History: {$historyPresent}
Patient Age: {$age} years
Gender: {$gender}

Provide ONLY valid JSON with:
{
  \"possible_diagnoses\": [
    {\"diagnosis\": \"name\", \"confidence\": 85, \"reasoning\": \"brief explanation\"}
  ],
  \"red_flags\": [\"critical findings to watch\"],
  \"recommended_tests\": [\"test names\"],
  \"treatment_suggestions\": [\"treatment options\"],
  \"follow_up_needed\": true
}

DO NOT include any text outside the JSON object.";
        
        $result = callAnthropicAPI($prompt, $api_key, $model);
        
        if (isset($result['error'])) {
            echo json_encode(['success' => false, 'message' => $result['error']]);
        } else {
            $responseText = $result['content'][0]['text'] ?? '';
            $responseText = preg_replace('/```json\n?/i', '', $responseText);
            $responseText = preg_replace('/```\n?/', '', $responseText);
            $responseText = trim($responseText);
            
            echo json_encode([
                'success' => true,
                'analysis' => json_decode($responseText, true)
            ]);
        }
        break;
        
    case 'check_interactions':
        $medications = $data['medications'] ?? [];
        $currentMeds = $data['current_medications'] ?? '';
        
        $medsString = implode(', ', $medications);
        
        $prompt = "Check for drug interactions between: {$medsString}

Include current medications: {$currentMeds}

Respond ONLY with valid JSON:
{
  \"has_interaction\": true,
  \"severity\": \"MAJOR\",
  \"interactions\": [
    {\"drugs\": [\"Drug A\", \"Drug B\"], \"effect\": \"description\", \"recommendation\": \"action\"}
  ]
}

DO NOT output anything other than valid JSON.";
        
        $result = callAnthropicAPI($prompt, $api_key, $model);
        
        if (isset($result['error'])) {
            echo json_encode(['success' => false, 'message' => $result['error']]);
        } else {
            $responseText = $result['content'][0]['text'] ?? '';
            $responseText = preg_replace('/```json\n?/i', '', $responseText);
            $responseText = preg_replace('/```\n?/', '', $responseText);
            $responseText = trim($responseText);
            
            echo json_encode([
                'success' => true,
                'interaction_data' => json_decode($responseText, true)
            ]);
        }
        break;
        
    case 'ask_question':
        $queryType = $data['query_type'] ?? '';
        $chiefComplaint = $data['chief_complaint'] ?? '';
        $historyPresent = $data['history_present'] ?? '';
        $diagnosis = $data['diagnosis'] ?? '';
        
        $prompt = '';
        
        switch ($queryType) {
            case 'suggest_diagnosis':
                $prompt = "Based on these symptoms, suggest possible ENT diagnoses:
Chief Complaint: {$chiefComplaint}
History: {$historyPresent}

Provide detailed clinical guidance.";
                break;
                
            case 'treatment_protocol':
                $prompt = "Provide evidence-based treatment protocol for: " . ($diagnosis ?: $chiefComplaint);
                break;
                
            case 'differential':
                $prompt = "List differential diagnoses for: {$chiefComplaint}

Provide detailed clinical reasoning.";
                break;
        }
        
        $result = callAnthropicAPI($prompt, $api_key, $model);
        
        if (isset($result['error'])) {
            echo json_encode(['success' => false, 'message' => $result['error']]);
        } else {
            $responseText = $result['content'][0]['text'] ?? '';
            echo json_encode([
                'success' => true,
                'response' => $responseText
            ]);
        }
        break;
        
    case 'chatbot_response':
        $message = $data['message'] ?? '';
        $sessionId = $data['session_id'] ?? '';
        $conversationId = $data['conversation_id'] ?? null;
        $messageHistory = $data['message_history'] ?? [];
        
        // Build conversation context
        $contextMessages = [];
        foreach ($messageHistory as $msg) {
            $role = $msg['sender_type'] === 'user' ? 'user' : 'assistant';
            $contextMessages[] = [
                'role' => $role,
                'content' => $msg['message_text']
            ];
        }
        
        // Add current message
        $contextMessages[] = [
            'role' => 'user',
            'content' => $message
        ];
        
        // Get hospital name from settings
        $hospital_name = getSetting($conn, 'hospital_name') ?: 'ENT Hospital';
        
        // Create system prompt
        $systemPrompt = "You are a helpful AI assistant for {$hospital_name}, specializing in ENT (Ear, Nose, and Throat) healthcare. 

Your role is to:
- Help patients book appointments
- Answer questions about ENT services, procedures, and conditions
- Provide general information about visiting hours, insurance, and payments
- Identify symptoms and suggest appropriate actions (but never diagnose)
- Handle emergency situations by escalating appropriately
- Be empathetic, professional, and clear

IMPORTANT: 
- Never diagnose or provide specific medical advice
- For urgent symptoms (severe bleeding, sudden hearing loss, difficulty breathing), recommend immediate emergency care
- For appointment booking, collect: patient name, contact, preferred date/time, reason for visit
- Always be supportive and understanding

Respond naturally and conversationally. Keep responses concise but helpful.";
        
        // Call Anthropic API with system prompt
        $ch = curl_init('https://api.anthropic.com/v1/messages');
        
        $payload = json_encode([
            'model' => $model,
            'max_tokens' => 1000,
            'system' => $systemPrompt,
            'messages' => $contextMessages
        ]);
        
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => $payload,
            CURLOPT_HTTPHEADER => [
                'Content-Type: application/json',
                'x-api-key: ' . $api_key,
                'anthropic-version: 2023-06-01'
            ],
            CURLOPT_TIMEOUT => 30,
            CURLOPT_SSL_VERIFYPEER => true
        ]);
        
        $response = curl_exec($ch);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $curl_error = curl_error($ch);
        curl_close($ch);
        
        if ($curl_error) {
            error_log("Chatbot CURL Error: " . $curl_error);
            echo json_encode(['success' => false, 'message' => 'Connection error: ' . $curl_error]);
            break;
        }
        
        if ($http_code !== 200) {
            error_log("Chatbot API Error (Code $http_code): " . $response);
            $error_data = json_decode($response, true);
            $error_message = $error_data['error']['message'] ?? 'Unknown error';
            echo json_encode(['success' => false, 'message' => "API Error ($http_code): $error_message"]);
            break;
        }
        
        $apiResponse = json_decode($response, true);
        $botMessage = $apiResponse['content'][0]['text'] ?? 'I apologize, but I encountered an error. Please try again.';
        
        // Detect intent
        $intent = 'general';
        $confidence = 0.7;
        
        $msg_lower = strtolower($message);
        if (strpos($msg_lower, 'appointment') !== false || strpos($msg_lower, 'book') !== false || strpos($msg_lower, 'schedule') !== false) {
            $intent = 'appointment';
            $confidence = 0.9;
        } elseif (strpos($msg_lower, 'pain') !== false || strpos($msg_lower, 'hurt') !== false || strpos($msg_lower, 'symptom') !== false) {
            $intent = 'symptoms';
            $confidence = 0.85;
        } elseif (strpos($msg_lower, 'emergency') !== false || strpos($msg_lower, 'urgent') !== false || strpos($msg_lower, 'bleeding') !== false) {
            $intent = 'emergency';
            $confidence = 0.95;
        } elseif (strpos($msg_lower, 'hours') !== false || strpos($msg_lower, 'open') !== false || strpos($msg_lower, 'time') !== false) {
            $intent = 'faq';
            $confidence = 0.8;
        } elseif (strpos($msg_lower, 'hello') !== false || strpos($msg_lower, 'hi') !== false || strpos($msg_lower, 'hey') !== false) {
            $intent = 'greeting';
            $confidence = 0.95;
        }
        
        // Save to database
        if (!$conversationId) {
            // Create new conversation
            $userType = 'staff';
            $userId = $_SESSION['user_id'];
            $ipAddress = $_SERVER['REMOTE_ADDR'] ?? null;
            $userAgent = $_SERVER['HTTP_USER_AGENT'] ?? null;
            
            $insertConv = "INSERT INTO chatbot_conversations 
                          (session_id, user_id, user_type, ip_address, user_agent, status) 
                          VALUES (?, ?, ?, ?, ?, 'active')";
            $stmt = $conn->prepare($insertConv);
            $stmt->bind_param("sisss", $sessionId, $userId, $userType, $ipAddress, $userAgent);
            $stmt->execute();
            $conversationId = $conn->insert_id;
            $stmt->close();
        }
        
        // Save user message
        $insertMsg = "INSERT INTO chatbot_messages 
                     (conversation_id, sender_type, message_text, message_type, intent, confidence_score) 
                     VALUES (?, 'user', ?, 'text', ?, ?)";
        $stmt = $conn->prepare($insertMsg);
        $stmt->bind_param("issd", $conversationId, $message, $intent, $confidence);
        $stmt->execute();
        $stmt->close();
        
        // Save bot response
        $insertBot = "INSERT INTO chatbot_messages 
                     (conversation_id, sender_type, message_text, message_type, intent, confidence_score) 
                     VALUES (?, 'bot', ?, 'text', ?, ?)";
        $stmt = $conn->prepare($insertBot);
        $stmt->bind_param("issd", $conversationId, $botMessage, $intent, $confidence);
        $stmt->execute();
        $stmt->close();
        
        // Update conversation last_activity
        $updateConv = "UPDATE chatbot_conversations SET last_activity = NOW() WHERE id = ?";
        $stmt = $conn->prepare($updateConv);
        $stmt->bind_param("i", $conversationId);
        $stmt->execute();
        $stmt->close();
        
        // Create analytics entry
        $insertAnalytics = "INSERT INTO chatbot_analytics 
                           (conversation_id, intent, resolved, message_count, date, hour) 
                           VALUES (?, ?, 0, 1, CURDATE(), HOUR(NOW()))
                           ON DUPLICATE KEY UPDATE message_count = message_count + 1";
        $stmt = $conn->prepare($insertAnalytics);
        $stmt->bind_param("is", $conversationId, $intent);
        $stmt->execute();
        $stmt->close();
        
        echo json_encode([
            'success' => true,
            'response' => $botMessage,
            'conversation_id' => $conversationId,
            'intent' => $intent,
            'confidence_score' => $confidence,
            'action_required' => null
        ]);
        break;
        
    case 'analyze_scheduling':
    $complaint = $data['complaint'] ?? '';
    $appointmentType = $data['appointment_type'] ?? '';
    $patientId = $data['patient_id'] ?? '';
    
    $prompt = "As an ENT clinic scheduler AI, analyze this appointment request:

Patient Complaint: {$complaint}
Appointment Type: {$appointmentType}

Respond ONLY with valid JSON (no markdown, no backticks):
{
  \"recommended_specialization\": \"string\",
  \"urgency_level\": \"ROUTINE|URGENT|EMERGENCY\",
  \"estimated_duration\": number,
  \"best_time_of_day\": \"MORNING|AFTERNOON|EVENING\",
  \"reasoning\": \"brief explanation\"
}";
    
    $result = callAnthropicAPI($prompt, $api_key, $model);
    
    if (isset($result['error'])) {
        echo json_encode(['success' => false, 'message' => $result['error']]);
    } else {
        $responseText = $result['content'][0]['text'] ?? '';
        $responseText = preg_replace('/```json\n?/i', '', $responseText);
        $responseText = preg_replace('/```\n?/', '', $responseText);
        $responseText = trim($responseText);
        
        echo json_encode([
            'success' => true,
            'analysis' => json_decode($responseText, true)
        ]);
    }
    break;    
        
    default:
        echo json_encode(['success' => false, 'message' => 'Invalid action']);
        break;
}
?>