xai-chatbot.php

This file implements the Howie chat widget for Try New Tech Logistics. It verifies the PHP session, injects user‐specific config into JavaScript, and renders a floating chat interface that communicates with the backend via WebSocket and REST APIs.

PHP Session & Configuration

The script first ensures a valid session. If $_SESSION['user_id'] is missing, it terminates with “Unauthorized access.”
It then safely escapes session variables and outputs them into a client‐side config object:

if (empty($_SESSION['user_id'])) {
    die("Unauthorized access");
}
$user_id = isset($_SESSION['user_id'])
    ? htmlspecialchars($_SESSION['user_id'], ENT_QUOTES, 'UTF-8')
    : '';
// ...
<script>
var config = {
    apiUrl: 'https://trynew.techlogistics.com:2053',
    wsUrl: 'wss://trynew.techlogistics.com:2053',
    userId: <?php echo json_encode($user_id); ?>,
    customerEmail: <?php echo json_encode($customer_email); ?>,
    customerId: <?php echo json_encode($customer_id); ?>,
    locationCode: <?php echo json_encode($company_code); ?>,
    defaultTraining: 'Intro'
};
</script>

HTML Structure

The widget is a fixed <div id="chatContainer"> with:

  • Header: Title, connection status, retry & close buttons
  • Training Info: <div id="chatTraining">
  • Messages: <div id="chatMessages">
  • Typing Indicator: <div id="typingIndicator">
  • Upload Progress: <div id="uploadProgress">
  • Input Area: <textarea> plus file, assistance, share, and send buttons
<div id="chatContainer">
  <div class="chat-header"> … </div>
  <div id="chatTraining"></div>
  <div id="chatMessages"></div>
  <div id="typingIndicator"></div>
  <div id="uploadProgress"></div>
  <div id="chatInput"> … </div>
</div>

CSS Styling

Inline <style> defines the widget’s look:

  • Layout: bottom-right fixed, flex column, shadowed box
  • Colors: blue header; distinct backgrounds for user, bot, agent
  • Responsive: adapts below 600 px width
#chatContainer { position: fixed; bottom: 10px; right: 10px; width: 540px; … }
.chat-header { background: #007bff; color: white; … }
#chatMessages div.user { background-color: #e3f2fd; text-align: right; … }
@media (max-width: 600px) {
  #chatContainer { width: 90%; } …
}

JavaScript Dependencies

  • jQuery 3.6.0
  • html2canvas 1.4.1
  • toastr for notifications
  • DOMPurify for safe HTML rendering
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/dompurify/2.4.0/purify.min.js"></script>

ChatManager Class

All client logic lives in ChatManager. It manages:

  • WebSocket connection & heartbeats
  • REST API calls (/api/chat, /api/upload, /api/messages, /api/chats)
  • UI updates: displaying messages, typing indicator, upload progress
  • Session persistence: via localStorage

Key Methods & Responsibilities

  • loadSetup / saveSetup: persist chatId & training
  • connectWebSocket: open WS, handle onopen, onmessage, onclose, onerror
  • displayMessage: render text or file link with appropriate styling
  • sendMessage: POST JSON to /api/chat and update setup.chatId
  • uploadFile: POST FormData to /api/upload then send a “File: …” message
  • fetchMessages: GET /api/messages to load historical messages
  • initializeChat: GET /api/chats to reuse or start a new chat
  • retryFetch: automatic retry logic for HTTP requests
  • debounce: throttle typing indicator events
  • init: wire up event listeners, trigger connection & chat init
document.addEventListener('DOMContentLoaded', function() {
  new ChatManager();
});

API Endpoints

POST /api/chat

{
  "title": "Send Chat Message",
  "description": "Sends a chat message or action to the server.",
  "method": "POST",
  "baseUrl": "https://trynew.techlogistics.com:2053",
  "endpoint": "/api/chat",
  "headers": [
    { "key": "Content-Type", "value": "application/json", "required": true }
  ],
  "bodyType": "json",
  "requestBody": "{\n  \"message\": \"Hello Howie\",\n  \"userId\": \"user_123\",\n  \"chatId\": null,\n  \"sender\": \"user\",\n  \"needsAssistance\": false,\n  \"originalName\": null,\n  \"page_url\": \"https://example.com/page\",\n  \"training\": \"Intro\",\n  \"customer_id\": \"cust_456\",\n  \"location_code\": \"LOC1\",\n  \"screenshot\": \"...\",\n  \"customer_email\": \"[email protected]\"\n}",
  "responses": {
    "200": {
      "description": "Message accepted",
      "body": "{\n  \"chatId\": 789\n}"
    },
    "400": {
      "description": "Invalid input",
      "body": "{ \"error\": { \"message\": \"Invalid userId\" } }"
    },
    "500": {
      "description": "Server error",
      "body": "{ \"error\": { \"message\": \"Internal server error\" } }"
    }
  }
}

POST /api/upload

{
  "title": "Upload Chat Attachment",
  "description": "Uploads a file and returns its server path for chat.",
  "method": "POST",
  "baseUrl": "https://trynew.techlogistics.com:2053",
  "endpoint": "/api/upload",
  "bodyType": "form",
  "formData": [
    { "key": "file", "value": "Binary file", "required": true }
  ],
  "responses": {
    "200": {
      "description": "Upload successful",
      "body": "{\n  \"filePath\": \"/uploads/doc.pdf\",\n  \"originalName\": \"report.pdf\"\n}"
    },
    "400": {
      "description": "Invalid file",
      "body": "{ \"error\": { \"message\": \"File type not allowed\" } }"
    },
    "500": {
      "description": "Server error",
      "body": "{ \"error\": { \"message\": \"Upload failed\" } }"
    }
  }
}

GET /api/messages

{
  "title": "Fetch Chat Messages",
  "description": "Retrieves messages for a chat since a given ID.",
  "method": "GET",
  "baseUrl": "https://trynew.techlogistics.com:2053",
  "endpoint": "/api/messages",
  "queryParams": [
    { "key": "chatId", "value": "ID of the chat session", "required": true },
    { "key": "lastId", "value": "Last received message ID", "required": false }
  ],
  "responses": {
    "200": {
      "description": "List of messages",
      "body": "[\n  {\n    \"id\": 1,\n    \"sender\": \"bot\",\n    \"message\": \"Welcome!\",\n    \"original_name\": null,\n    \"created_at\": \"2025-09-19T12:34:56Z\"\n  }\n]"
    },
    "400": {
      "description": "Missing parameters",
      "body": "{ \"error\": { \"message\": \"chatId is required\" } }"
    },
    "500": {
      "description": "Server error",
      "body": "{ \"error\": { \"message\": \"Unable to fetch messages\" } }"
    }
  }
}

GET /api/chats

{
  "title": "List User Chats",
  "description": "Retrieves all chat sessions for a user.",
  "method": "GET",
  "baseUrl": "https://trynew.techlogistics.com:2053",
  "endpoint": "/api/chats",
  "queryParams": [
    { "key": "userId", "value": "ID of the user", "required": true }
  ],
  "responses": {
    "200": {
      "description": "User chat sessions",
      "body": "[\n  {\n    \"id\": 789,\n    \"user_id\": \"user_123\",\n    \"created_at\": \"2025-09-19T11:00:00Z\"\n  }\n]"
    },
    "400": {
      "description": "Missing userId",
      "body": "{ \"error\": { \"message\": \"userId is required\" } }"
    },
    "500": {
      "description": "Server error",
      "body": "{ \"error\": { \"message\": \"Unable to list chats\" } }"
    }
  }
}

Message Flow Sequence

When a user sends a message, the widget uses both HTTP and WebSocket:

sequenceDiagram
    participant User
    participant Widget as Chat Widget
    participant API as REST API
    participant WS as WebSocket Server

    User->>Widget: Types & sends message  
    Widget->>API: POST /api/chat  
    API-->>Widget: { "chatId": 123 }  
    WS-->>Widget: {"type":"message","message":"Hello","sender":"bot"}  
    Widget->>User: Displays bot response  

This diagram illustrates the core chat loop: POST for sending and WebSocket for live incoming messages.