<?php
/**
 * Public Chatbot API Endpoint
 * Handles chatbot interactions from external website visitors (guests)
 * No authentication required
 */

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

// Handle preflight requests
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

// Only allow POST requests
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'error' => 'Method not allowed']);
    exit();
}

include '../layouts/dbconn.php';

// Get JSON input
$input = json_decode(file_get_contents('php://input'), true);

// Validate input
if (!isset($input['message']) || !isset($input['session_id'])) {
    echo json_encode(['success' => false, 'error' => 'Missing required fields']);
    exit();
}

$message = trim($input['message']);
$session_id = $input['session_id'];
$conversation_id = $input['conversation_id'] ?? null;
$user_agent = $input['user_agent'] ?? $_SERVER['HTTP_USER_AGENT'] ?? '';
$referrer = $input['referrer'] ?? $_SERVER['HTTP_REFERER'] ?? '';
$ip_address = $_SERVER['REMOTE_ADDR'] ?? '';

// Validate message length
if (strlen($message) < 1 || strlen($message) > 1000) {
    echo json_encode(['success' => false, 'error' => 'Message must be between 1 and 1000 characters']);
    exit();
}

try {
    // Start transaction
    $conn->begin_transaction();
    
    // Get or create conversation
    if ($conversation_id) {
        // Verify conversation exists and belongs to this session
        $stmt = $conn->prepare("SELECT id, status FROM chatbot_conversations WHERE id = ? AND session_id = ?");
        $stmt->bind_param("is", $conversation_id, $session_id);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($result->num_rows === 0) {
            $conversation_id = null; // Invalid conversation, create new one
        } else {
            $conv = $result->fetch_assoc();
            // If conversation is closed, create new one
            if ($conv['status'] === 'closed') {
                $conversation_id = null;
            }
        }
        $stmt->close();
    }
    
    // Create new conversation if needed
    if (!$conversation_id) {
        $stmt = $conn->prepare("
            INSERT INTO chatbot_conversations 
            (session_id, user_id, user_type, ip_address, user_agent, status) 
            VALUES (?, NULL, 'guest', ?, ?, 'active')
        ");
        $stmt->bind_param("sss", $session_id, $ip_address, $user_agent);
        $stmt->execute();
        $conversation_id = $conn->insert_id;
        $stmt->close();
    } else {
        // Update last activity
        $stmt = $conn->prepare("UPDATE chatbot_conversations SET last_activity = CURRENT_TIMESTAMP WHERE id = ?");
        $stmt->bind_param("i", $conversation_id);
        $stmt->execute();
        $stmt->close();
    }
    
    // Save user message
    $stmt = $conn->prepare("
        INSERT INTO chatbot_messages 
        (conversation_id, sender_type, message_text, message_type, created_at) 
        VALUES (?, 'user', ?, 'text', CURRENT_TIMESTAMP)
    ");
    $stmt->bind_param("is", $conversation_id, $message);
    $stmt->execute();
    $stmt->close();
    
    // Process message and get intent
    $intent_data = detectIntent($conn, $message);
    $intent = $intent_data['intent'];
    $confidence = $intent_data['confidence'];
    $action_required = $intent_data['action'];
    
    // Generate response
    $response = generateResponse($conn, $message, $intent, $conversation_id);
    
    // Save bot response
    $metadata = json_encode([
        'intent' => $intent,
        'confidence' => $confidence,
        'action' => $action_required,
        'referrer' => $referrer
    ]);
    
    $stmt = $conn->prepare("
        INSERT INTO chatbot_messages 
        (conversation_id, sender_type, message_text, message_type, intent, confidence_score, metadata, created_at) 
        VALUES (?, 'bot', ?, 'text', ?, ?, ?, CURRENT_TIMESTAMP)
    ");
    $stmt->bind_param("issds", $conversation_id, $response, $intent, $confidence, $metadata);
    $stmt->execute();
    $stmt->close();
    
    // Update analytics
    updateAnalytics($conn, $conversation_id, $intent, $action_required);
    
    // Check for escalation keywords
    $escalation_keywords = getSetting($conn, 'chatbot_escalation_keywords');
    $should_escalate = checkEscalation($message, $escalation_keywords);
    
    if ($should_escalate) {
        // Update conversation status
        $stmt = $conn->prepare("UPDATE chatbot_conversations SET status = 'escalated' WHERE id = ?");
        $stmt->bind_param("i", $conversation_id);
        $stmt->execute();
        $stmt->close();
        
        // Add escalation notice
        $escalation_phone = getSetting($conn, 'chatbot_escalation_phone');
        $response .= "\n\nFor immediate assistance, please call us at " . $escalation_phone;
        $action_required = 'show_emergency';
    }
    
    // Commit transaction
    $conn->commit();
    
    // Prepare response
    $output = [
        'success' => true,
        'response' => $response,
        'conversation_id' => $conversation_id,
        'intent' => $intent,
        'confidence_score' => $confidence,
        'action_required' => $action_required,
        'action_data' => getActionData($action_required)
    ];
    
    echo json_encode($output);
    
} catch (Exception $e) {
    $conn->rollback();
    error_log('Chatbot error: ' . $e->getMessage());
    echo json_encode([
        'success' => false,
        'error' => 'An error occurred. Please try again.',
        'response' => 'I apologize, but I encountered a technical issue. Please try again or contact our support team.'
    ]);
}

/**
 * Detect intent from user message
 */
function detectIntent($conn, $message) {
    $message_lower = strtolower($message);
    
    // Get all active intents
    $sql = "SELECT intent_name, category, training_phrases, action_required, priority 
            FROM chatbot_intents 
            WHERE is_active = 1 
            ORDER BY priority DESC";
    $result = $conn->query($sql);
    
    $best_match = [
        'intent' => 'general',
        'confidence' => 0.0,
        'action' => null
    ];
    
    while ($row = $result->fetch_assoc()) {
        $phrases = json_decode($row['training_phrases'], true);
        if (!$phrases) continue;
        
        $match_count = 0;
        foreach ($phrases as $phrase) {
            if (strpos($message_lower, strtolower($phrase)) !== false) {
                $match_count++;
            }
        }
        
        if ($match_count > 0) {
            $confidence = min(1.0, $match_count / count($phrases));
            
            // Apply priority boost
            $confidence += ($row['priority'] * 0.05);
            
            if ($confidence > $best_match['confidence']) {
                $best_match = [
                    'intent' => $row['category'],
                    'confidence' => min(1.0, $confidence),
                    'action' => $row['action_required']
                ];
            }
        }
    }
    
    // Check symptoms
    if ($best_match['confidence'] < 0.5) {
        $symptom_match = checkSymptoms($conn, $message);
        if ($symptom_match['confidence'] > $best_match['confidence']) {
            $best_match = $symptom_match;
        }
    }
    
    return $best_match;
}

/**
 * Check for symptom matches
 */
function checkSymptoms($conn, $message) {
    $message_lower = strtolower($message);
    
    $sql = "SELECT symptom_name, keywords, severity_level, recommended_action, urgency_score 
            FROM chatbot_symptoms 
            WHERE ent_related = 1 
            ORDER BY urgency_score DESC";
    $result = $conn->query($sql);
    
    $best_match = [
        'intent' => 'symptoms',
        'confidence' => 0.0,
        'action' => null,
        'severity' => null
    ];
    
    while ($row = $result->fetch_assoc()) {
        $keywords = explode(',', $row['keywords']);
        $match_count = 0;
        
        foreach ($keywords as $keyword) {
            if (strpos($message_lower, trim(strtolower($keyword))) !== false) {
                $match_count++;
            }
        }
        
        if ($match_count > 0) {
            $confidence = min(1.0, $match_count / count($keywords));
            
            if ($confidence > $best_match['confidence']) {
                $best_match = [
                    'intent' => 'symptoms',
                    'confidence' => $confidence,
                    'action' => $row['severity_level'] === 'critical' ? 'show_emergency' : 'book_appointment',
                    'severity' => $row['severity_level']
                ];
            }
        }
    }
    
    return $best_match;
}

/**
 * Generate response based on intent
 */
function generateResponse($conn, $message, $intent, $conversation_id) {
    // Try to get response from intents
    $stmt = $conn->prepare("SELECT responses FROM chatbot_intents WHERE category = ? AND is_active = 1 LIMIT 1");
    $stmt->bind_param("s", $intent);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($row = $result->fetch_assoc()) {
        $responses = json_decode($row['responses'], true);
        if ($responses && count($responses) > 0) {
            $response = $responses[array_rand($responses)];
            $stmt->close();
            
            // Replace placeholders
            $hospital_name = getSetting($conn, 'hospital_name');
            $response = str_replace('[Hospital Name]', $hospital_name, $response);
            
            return $response;
        }
    }
    $stmt->close();
    
    // Try knowledge base
    $response = searchKnowledgeBase($conn, $message);
    if ($response) {
        return $response;
    }
    
    // Default response
    $chatbot_name = getSetting($conn, 'chatbot_name');
    return "Thank you for your message. I'm " . $chatbot_name . ", and I'm here to help. Could you please provide more details or try rephrasing your question?";
}

/**
 * Search knowledge base
 */
function searchKnowledgeBase($conn, $message) {
    $message_lower = strtolower($message);
    $words = preg_split('/\s+/', $message_lower);
    $search_terms = array_filter($words, function($word) {
        return strlen($word) > 3; // Only use words longer than 3 chars
    });
    
    if (empty($search_terms)) {
        return null;
    }
    
    $sql = "SELECT answer, keywords 
            FROM chatbot_knowledge_base 
            WHERE is_active = 1";
    $result = $conn->query($sql);
    
    $best_match = null;
    $best_score = 0;
    
    while ($row = $result->fetch_assoc()) {
        $keywords = explode(',', strtolower($row['keywords']));
        $score = 0;
        
        foreach ($search_terms as $term) {
            foreach ($keywords as $keyword) {
                if (strpos(trim($keyword), $term) !== false || strpos($term, trim($keyword)) !== false) {
                    $score++;
                }
            }
        }
        
        if ($score > $best_score) {
            $best_score = $score;
            $best_match = $row['answer'];
        }
    }
    
    return $best_score > 0 ? $best_match : null;
}

/**
 * Check for escalation triggers
 */
function checkEscalation($message, $keywords_string) {
    if (empty($keywords_string)) {
        return false;
    }
    
    $keywords = array_map('trim', explode(',', strtolower($keywords_string)));
    $message_lower = strtolower($message);
    
    foreach ($keywords as $keyword) {
        if (strpos($message_lower, $keyword) !== false) {
            return true;
        }
    }
    
    return false;
}

/**
 * Update analytics
 */
function updateAnalytics($conn, $conversation_id, $intent, $action) {
    // Check if analytics record exists
    $stmt = $conn->prepare("SELECT id FROM chatbot_analytics WHERE conversation_id = ?");
    $stmt->bind_param("i", $conversation_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows > 0) {
        // Update existing
        $stmt = $conn->prepare("
            UPDATE chatbot_analytics 
            SET intent = ?, 
                message_count = message_count + 1,
                escalated = CASE WHEN ? = 'show_emergency' THEN 1 ELSE escalated END
            WHERE conversation_id = ?
        ");
        $stmt->bind_param("ssi", $intent, $action, $conversation_id);
    } else {
        // Create new
        $escalated = ($action === 'show_emergency') ? 1 : 0;
        $stmt = $conn->prepare("
            INSERT INTO chatbot_analytics 
            (conversation_id, intent, message_count, escalated, date) 
            VALUES (?, ?, 1, ?, CURDATE())
        ");
        $stmt->bind_param("isi", $conversation_id, $intent, $escalated);
    }
    
    $stmt->execute();
    $stmt->close();
}

/**
 * Get action-specific data
 */
function getActionData($action) {
    switch ($action) {
        case 'book_appointment':
            return [
                'url' => '/book_appointment.php',
                'message' => 'Click here to book your appointment'
            ];
        case 'show_emergency':
            return [
                'phone' => getSetting($GLOBALS['conn'], 'chatbot_escalation_phone'),
                'message' => 'For emergencies, please call immediately'
            ];
        default:
            return null;
    }
}

/**
 * Get system setting
 */
function getSetting($conn, $key) {
    $stmt = $conn->prepare("SELECT setting_value FROM system_settings WHERE setting_key = ?");
    $stmt->bind_param("s", $key);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($row = $result->fetch_assoc()) {
        return $row['setting_value'];
    }
    
    return '';
}
?>