'No message provided.']); exit; } // --- Context Gathering --- $context = ""; try { $pdo = db(); // Fetch candidates $stmt = $pdo->query("SELECT name, status, email FROM candidates ORDER BY created_at DESC LIMIT 10"); $candidates = $stmt->fetchAll(PDO::FETCH_ASSOC); $context .= "\n\nRecent Candidates:\n" . json_encode($candidates, JSON_PRETTY_PRINT); // Fetch tasks $stmt = $pdo->query("SELECT t.task_name, c.name as assigned_to, t.status, t.due_date FROM tasks t JOIN candidates c ON t.candidate_id = c.id ORDER BY t.created_at DESC LIMIT 10"); $tasks = $stmt->fetchAll(PDO::FETCH_ASSOC); $context .= "\n\nRecent Tasks:\n" . json_encode($tasks, JSON_PRETTY_PRINT); } catch (PDOException $e) { // Don't expose DB errors to the user, but log them. error_log("AI Chat Context Error: " . $e->getMessage()); // Provide a fallback context $context = "\n\nCould not fetch real-time data. Please rely on general knowledge."; } // --- AI Interaction --- $systemPrompt = << 'system', 'content' => $systemPrompt], ['role' => 'user', 'content' => $userMessage] ]; $response = LocalAIApi::createResponse([ 'input' => $messages, ]); if (!empty($response['success'])) { $decoded = LocalAIApi::decodeJsonFromResponse($response); $aiReply = $decoded['choices'][0]['message']['content'] ?? 'Sorry, I could not process that.'; echo json_encode(['reply' => $aiReply]); } else { error_log('AI error: ' . ($response['error'] ?? 'unknown')); echo json_encode(['error' => 'Failed to get a response from the AI.']); } ?>