'An unexpected error occurred.', 'message' => $exception->getMessage(), 'file' => $exception->getFile(), 'line' => $exception->getLine(), ]; file_put_contents($logFile, json_encode($error, JSON_PRETTY_PRINT)); // We must output valid JSON, otherwise the frontend will get a syntax error. echo json_encode($error); }); require_once __DIR__ . '/../lib/config.php'; require_once __DIR__ . '/../lib/OpenAIService.php'; require_once __DIR__ . '/../db/config.php'; // The main try-catch block for the application logic. try { // Check if it's a POST request if ($_SERVER['REQUEST_METHOD'] !== 'POST') { http_response_code(405); // Method Not Allowed throw new Exception('Only POST requests are allowed.'); } // Get the user's message from the request body $json_data = file_get_contents('php://input'); $data = json_decode($json_data); $user_message = $data->message ?? ''; if (empty($user_message)) { http_response_code(400); // Bad Request throw new Exception('Message is required.'); } // --- Database Interaction --- $pdo = db(); if (empty($_SESSION['chat_session_id'])) { $_SESSION['chat_session_id'] = bin2hex(random_bytes(16)); } $chat_session_id = $_SESSION['chat_session_id']; // Log the user's message $stmt = $pdo->prepare("INSERT INTO chat_log (session_id, sender, message) VALUES (?, ?, ?)"); $stmt->execute([$chat_session_id, 'user', $user_message]); // --- OpenAI API Call --- $bot_response_data = OpenAIService::getCompletion($user_message); if (isset($bot_response_data['error'])) { throw new Exception('OpenAI API Error: ' . $bot_response_data['error']); } $bot_response = $bot_response_data['reply']; // Log the bot's response $stmt = $pdo->prepare("INSERT INTO chat_log (session_id, sender, message) VALUES (?, ?, ?)"); $stmt->execute([$chat_session_id, 'bot', $bot_response]); // --- Send Response --- header('Content-Type: application/json'); echo json_encode(['reply' => $bot_response]); } catch (Throwable $e) { // This will catch both Exceptions and Errors http_response_code(500); $errorDetails = [ 'error' => 'Caught in main try-catch', 'message' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine(), 'trace' => $e->getTraceAsString() ]; file_put_contents($logFile, date('Y-m-d H:i:s') . " - " . json_encode($errorDetails, JSON_PRETTY_PRINT) . " ", FILE_APPEND); // Ensure a JSON response is sent on error header('Content-Type: application/json'); echo json_encode($errorDetails); }