$message";
}
}
// Handle form submission
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$userMessage = $_POST['userMessage'];
if (!empty($userMessage)) {
$_SESSION['chat_history'][] = "User: " . htmlspecialchars($userMessage);
// OpenAI API request logic
$apiKey = 'YOUR_OPENAI_API_KEY'; // Replace with your API key
$url = 'https://api.openai.com/v1/chat/completions';
$data = [
'model' => 'gpt-3.5-turbo',
'messages' => [['role' => 'user', 'content' => $userMessage]],
];
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Bearer ' . $apiKey,
]);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
$response = curl_exec($ch);
curl_close($ch);
// Decode the JSON response
$responseData = json_decode($response, true);
$botResponse = isset($responseData['choices'][0]['message']['content']) ? $responseData['choices'][0]['message']['content'] : "Sorry, I couldn't process that.";
$_SESSION['chat_history'][] = "Bot: " . htmlspecialchars($botResponse);
} else {
echo "
Error: Message is empty
";
}
}
?>