<?php
/**
 * Internal Chatbot API Endpoint
 * Handles chatbot interactions for logged-in staff members
 * Requires authentication
 */

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

// Check authentication
if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'error' => 'Unauthorized']);
    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;
$message_history = $input['message_history'] ?? [];
$user_id = $_SESSION['user_id'];
$ip_address = $_SERVER['REMOTE_ADDR'] ?? '';
$user_agent = $_SERVER['HTTP_USER_AGENT'] ?? '';

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

try {
    // Start transaction
    $conn->begin_transaction();
    
    // Get or create conversation for staff user
    if ($conversation_id) {
        // Verify conversation exists and belongs to this user
        $stmt = $conn->prepare("SELECT id, status FROM chatbot_conversations WHERE id = ? AND user_id = ?");
        $stmt->bind_param("ii", $conversation_id, $user_id);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($result->num_rows === 0) {
            $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 (?, ?, 'staff', ?, ?, 'active')
        ");
        $stmt->bind_param("siss", $session_id, $user_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 (reuse public function)
    include_once 'chatbot_public.php';
    $intent_data = detectIntent($conn, $message);
    $intent = $intent_data['intent'];
    $confidence = $intent_data['confidence'];
    $action_required = $intent_data['action'];
    
    // Generate response (staff get more detailed responses)
    $response = generateStaffResponse($conn, $message, $intent, $conversation_id, $message_history);
    
    // Save bot response
    $metadata = json_encode([
        'intent' => $intent,
        'confidence' => $confidence,
        'action' => $action_required,
        'user_type' => 'staff'
    ]);
    
    $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);
    
    // 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('Staff 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.'
    ]);
}

/**
 * Generate response for staff users (more detailed)
 */
function generateStaffResponse($conn, $message, $intent, $conversation_id, $history) {
    // Staff get enhanced responses with additional context
    $response = generateResponse($conn, $message, $intent, $conversation_id);
    
    // Add staff-specific information
    switch ($intent) {
        case 'appointment':
            $response .= "\n\n📊 You can manage appointments in the Appointments module.";
            break;
        case 'symptoms':
            $response .= "\n\n💡 For patient triage, use the Clinical Assessment module.";
            break;
        case 'emergency':
            $response .= "\n\n🚨 Follow emergency protocols in the Emergency Response section.";
            break;
    }
    
    return $response;
}
?>