$full_prompt); // Extract the response from the tool's output // The exact structure of the response may vary. $ai_message = $api_response['answer'] ?? 'Sorry, I could not get a response from the AI.'; return $ai_message; */ // For now, return a simulated response that includes the prompt. return "(Simulated AI Response with API Key. Based on prompt: '" . $prompt . "')"; } if ($_SERVER['REQUEST_METHOD'] === 'POST') { $data = json_decode(file_get_contents('php://input'), true); if (isset($data['lead_id']) && isset($data['message'])) { $lead_id = $data['lead_id']; $message = $data['message']; try { $pdo = db(); // Save user message $stmt = $pdo->prepare("INSERT INTO messages (lead_id, sender, message) VALUES (?, 'user', ?)"); $stmt->execute([$lead_id, $message]); $user_message_id = $pdo->lastInsertId(); // Fetch settings $stmt = $pdo->query("SELECT * FROM settings"); $settings = $stmt->fetchAll(PDO::FETCH_KEY_PAIR); $apiKey = $settings['api_key'] ?? ''; $aiPrompt = $settings['ai_prompt'] ?? 'You are a helpful assistant.'; // Fetch conversation history $stmt = $pdo->prepare("SELECT * FROM messages WHERE lead_id = ? ORDER BY created_at ASC"); $stmt->execute([$lead_id]); $conversation_history = $stmt->fetchAll(); // Get AI response $ai_message = get_gemini_response($apiKey, $aiPrompt, $conversation_history, $message); $stmt = $pdo->prepare("INSERT INTO messages (lead_id, sender, message) VALUES (?, 'ai', ?)"); $stmt->execute([$lead_id, $ai_message]); $ai_message_id = $pdo->lastInsertId(); // Fetch the created messages to return them $stmt = $pdo->prepare("SELECT * FROM messages WHERE id IN (?, ?)"); $stmt->execute([$user_message_id, $ai_message_id]); $new_messages = $stmt->fetchAll(); echo json_encode(['success' => true, 'messages' => $new_messages]); } catch (PDOException $e) { http_response_code(500); echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]); } } else { http_response_code(400); echo json_encode(['success' => false, 'message' => 'Invalid input']); } } else { http_response_code(405); echo json_encode(['success' => false, 'message' => 'Method not allowed']); }