35851-vm/results.php
2025-11-19 15:51:26 +00:00

255 lines
9.9 KiB
PHP

<?php
// results.php
require_once __DIR__ . '/ai/LocalAIApi.php';
$conversation_json = $_POST['conversation'] ?? '';
$conversation = json_decode($conversation_json, true);
$ai_response_text = '';
$chart_data_json = '';
$error_message = '';
if ($conversation) {
$prompt = "Analyze the following conversation for signs of burnout. The user was asked 10 questions related to burnout. Based on their answers, provide a thoughtful analysis and actionable recommendations. Return a JSON object with two keys: 'analysis_html' and 'chart_data'.\n\n1. `analysis_html`: An HTML string containing a detailed analysis, identifying key themes (e.g., exhaustion, cynicism, inefficacy), a summary of the user's burnout level, and 3-5 actionable recommendations. Use headings, lists, and bold text for readability. Do not include `<html>` or `<body>` tags.\n2. `chart_data`: A JSON object with two keys: `labels` (an array of strings for the chart categories, e.g., ['Exhaustion', 'Cynicism', 'Inefficacy']) and `scores` (an array of integers from 0 to 10 representing the user's score in each category).\n\nHere is the conversation:
";
foreach ($conversation as $item) {
$prompt .= "Q: " . $item['question'] . "\nA: " . $item['answer'] . "\n\n";
}
$resp = LocalAIApi::createResponse(
[
'input' => [
['role' => 'system', 'content' => 'You are a helpful assistant specializing in mental health and burnout analysis. You always respond with a valid JSON object.'],
['role' => 'user', 'content' => $prompt],
],
]
);
if (!empty($resp['success'])) {
$ai_response_raw = LocalAIApi::extractText($resp);
$ai_response_data = json_decode($ai_response_raw, true);
if ($ai_response_data && isset($ai_response_data['analysis_html']) && isset($ai_response_data['chart_data'])) {
$ai_response_text = $ai_response_data['analysis_html'];
$chart_data_json = json_encode($ai_response_data['chart_data']);
} else {
$error_message = 'AI response was not in the expected format. Please try again.';
// For debugging: $error_message .= "<br>Raw response: " . htmlspecialchars($ai_response_raw);
}
} else {
$error_message = 'Failed to get response from AI. Error: ' . ($resp['error'] ?? 'Unknown error');
}
} else {
$error_message = 'No conversation data received.';
}
?><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Your Burnout Analysis Results</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600&display=swap" rel="stylesheet">
<link rel="stylesheet" href="assets/css/custom.css?v=<?php echo time(); ?>">
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<style>
.results-container {
width: 100%;
max-width: 768px;
background-color: #FFFFFF;
border-radius: 0.75rem;
box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
padding: 2rem;
text-align: left;
}
.loader {
border: 4px solid #f3f4f6;
border-radius: 50%;
border-top: 4px solid #4F46E5;
width: 40px;
height: 40px;
animation: spin 1s linear infinite;
margin: 2rem auto;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
.ai-content h2 {
font-size: 1.5rem;
color: #4F46E5;
margin-top: 1.5rem;
margin-bottom: 1rem;
}
.ai-content ul {
list-style-position: inside;
padding-left: 0;
}
.ai-content li {
margin-bottom: 0.75rem;
line-height: 1.6;
}
#burnoutChart {
margin-top: 2rem;
margin-bottom: 2rem;
}
</style>
</head>
<body>
<div class="chat-container">
<header class="chat-header">
<h1>Your Burnout Analysis</h1>
</header>
<main class="message-list" id="results-main">
<div class="results-container">
<?php if ($error_message): ?>
<p style="color: red;"><?php echo htmlspecialchars($error_message); ?></p>
<?php elseif ($ai_response_text): ?>
<canvas id="burnoutChart"></canvas>
<div class="ai-content">
<?php echo $ai_response_text; ?>
</div>
<?php else: ?>
<p>Analyzing your responses...</p>
<div class="loader"></div>
<?php endif; ?>
</div>
</main>
<?php if (!$error_message && $ai_response_text): ?>
<footer id="input-area" class="input-area">
<input type="text" id="user-input" placeholder="Ask a follow-up question..." autocomplete="off">
<button id="send-button">Send</button>
</footer>
<?php endif; ?>
</div>
<?php if ($chart_data_json): ?>
<script>
document.addEventListener('DOMContentLoaded', () => {
const chartData = <?php echo $chart_data_json; ?>;
const ctx = document.getElementById('burnoutChart').getContext('2d');
new Chart(ctx, {
type: 'radar',
data: {
labels: chartData.labels,
datasets: [{
label: 'Burnout Score',
data: chartData.scores,
backgroundColor: 'rgba(79, 70, 229, 0.2)',
borderColor: '#4F46E5',
pointBackgroundColor: '#4F46E5',
pointBorderColor: '#fff',
pointHoverBackgroundColor: '#fff',
pointHoverBorderColor: '#4F46E5'
}]
},
options: {
responsive: true,
maintainAspectRatio: true,
scales: {
r: {
angleLines: {
color: '#E5E7EB'
},
grid: {
color: '#E5E7EB'
},
pointLabels: {
font: {
size: 14,
family: 'Inter'
},
color: '#111827'
},
ticks: {
backdropColor: '#f3f4f6',
color: '#6B7280',
stepSize: 2,
beginAtZero: true,
max: 10
}
}
},
plugins: {
legend: {
display: false
}
}
}
});
});
</script>
<?php endif; ?>
<?php if (!$error_message && $ai_response_text): ?>
<script>
document.addEventListener('DOMContentLoaded', () => {
const sendButton = document.getElementById('send-button');
const userInput = document.getElementById('user-input');
const mainContainer = document.getElementById('results-main');
const originalConversation = <?php echo json_encode($conversation); ?>;
const originalAnalysis = <?php echo json_encode($ai_response_text); ?>;
function addMessageToUI(text, sender) {
const messageElement = document.createElement('div');
messageElement.classList.add('message', sender);
const avatar = document.createElement('div');
avatar.classList.add('avatar');
avatar.textContent = sender === 'bot' ? 'AI' : 'You';
const messageContent = document.createElement('div');
messageContent.classList.add('message-content');
messageContent.innerHTML = text; // Use innerHTML to render formatted AI responses
if (sender === 'bot') {
messageElement.appendChild(avatar);
}
messageElement.appendChild(messageContent);
mainContainer.appendChild(messageElement);
mainContainer.scrollTop = mainContainer.scrollHeight;
}
async function handleFollowUp() {
const userText = userInput.value.trim();
if (userText === '') return;
addMessageToUI(userText, 'user');
userInput.value = '';
sendButton.disabled = true;
const response = await fetch('followup.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
conversation: originalConversation,
analysis: originalAnalysis,
follow_up_question: userText
})
});
const aiResponseText = await response.text();
addMessageToUI(aiResponseText, 'bot');
sendButton.disabled = false;
userInput.focus();
}
sendButton.addEventListener('click', handleFollowUp);
userInput.addEventListener('keydown', (e) => {
if (e.key === 'Enter') {
handleFollowUp();
}
});
});
</script>
<?php endif; ?>
</body>
</html>