linuxfront-v2-logistics/xai-opt.php
🚀 Overview
This file implements a chat widget named “Howie!” for TryNewTechLogistics. It combines a PHP preamble for session handling with a self-contained HTML/CSS/JavaScript UI. The script connects via WebSocket and REST calls to a back-end chat API, manages file uploads, typing indicators, and human-assistance requests.
🔧 PHP Session & Configuration
At the top, the script starts a session, dumps its contents for debugging, and configures error logging:
<?php
session_start(); // Start PHP session
echo '<pre>'; print_r($_SESSION); exit; // DEBUG: dump and halt
error_reporting(E_ALL);
ini_set('display_errors', 0);
ini_set('log_errors', 1);
ini_set('error_log', '/home/jdobbins/trynewtechlogistics/php_error.log');
header('Content-Type: text/html; charset=UTF-8');
All session variables are sanitized with htmlspecialchars() and given safe defaults:
| Variable | Source | Default |
|---|---|---|
| $user_id | $_SESSION['user_id'] |
'guest_' . uniqid() |
| $customer_email | $_SESSION['Customer_email'] |
'' |
| $customer_id | $_SESSION['Customer_ID'] |
'' |
| $company_code | $_SESSION['company_code'] |
'' |
📐 HTML Structure
The UI markup uses semantic containers:
#chatContainer– holds the chat header, status, messages, indicators, and inputs.#chatTraining– displays the current “training” context.#chatMessages– scrollable history of messages.#typingIndicator– shows “Howie is typing…” dots.#chatInput– textarea, attach‐file button, and send button.#needsAssistanceButton– requests human handoff.#chatIcon– floating button to toggle visibility.
🎨 CSS Styling
Inline styles define a modern, responsive look:
| Selector | Purpose |
|---|---|
body |
Global font, padding, light background |
#chatContainer |
Centered card, shadow, rounded corners |
#chatMessages div.user |
Blue bubble (user messages) |
#chatMessages div.bot |
Grey bubble (Howie responses) |
#chatMessages div.agent |
Orange‐tinted (human agent) |
#connectionStatus.connected |
Green badge |
#connectionStatus.disconnected |
Red badge |
| Media queries | Ensure mobile adaptability |
🧠 JavaScript Logic (ChatManager)
A prototypal class orchestrates all chat behaviors:
Key Properties
setup– persisted config (userId, chatId, training, etc.)ws– WebSocket instancedisplayedMessages– Set of message IDs to avoid duplicateslastMessageId– highest‐seen message IDreconnectAttempts– for exponential backoff
Main Methods
| Method | Description |
|---|---|
| loadSetup() / saveSetup() | Read/write localStorage chat settings |
| connectWebSocket() | Open WS, handle open/message/close/error, with backoff |
| displayMessage(data) | Inject sanitized HTML for text or file messages |
| sendMessage(msg,…) | POST /api/chat, update chatId, show errors via Toastr |
| uploadFile(file) | POST /api/upload, then sendMessage("File: "+path) |
| fetchMessages() | GET /api/messages?chatId=…&lastId=… and render new ones |
| initializeChat() | GET /api/chats?userId=…, start new chat or load last one |
| retryFetch() | Generic fetch with retries |
| debounce(func, wait) | Throttle typing‐indicator events |
| init() | Wire all UI event listeners and trigger connect + init |
🔄 Message Flow
A sequence diagram clarifies the interaction between the user, front-end, WebSocket server, and REST API:
sequenceDiagram
participant U as User
participant F as Frontend (xai-opt.php)
participant WS as WebSocket Server
participant API as REST API Server
U->>F: Page Load
F->>F: new ChatManager().init()
F->>WS: connectWebSocket(userId)
WS-->>F: onopen → Connected
F->>API: GET /api/chats?userId
API-->>F: [chats]
Note over F: start or resume chat
U->>F: Enters message + Send
F->>API: POST /api/chat
API-->>F: { chatId }
API->>WS: broadcast message
WS-->>F: onmessage(type=message)
F->>F: displayMessage(...)
🚀 User Interactions
- Send: click “Send” or press Enter (no Shift)
- Typing: debounced WS “typing” events
- Attach File: click paperclip, choose file → upload
- Request Assistance: click “Request Human Assistance”
- Toggle Chat: click floating chat icon
All events funnel through ChatManager methods and update the UI in real time.
🔐 Security & Sanitization
- PHP: uses
htmlspecialchars()on all session inputs - JS: sanitizes all incoming HTML with [DOMPurify]
- CORS / Cookies: relies on
credentials: 'include'for secure cookie handling
⚙️ API Endpoints
| Endpoint | Method | Purpose |
|---|---|---|
/api/chat |
POST | Send a chat message |
/api/upload |
POST | Upload a file and return its server path |
/api/messages |
GET | Fetch new messages since lastId |
/api/chats |
GET | List or start chat sessions for a user |
All requests include JSON bodies and credentials for session continuity.
📦 Integration & Usage
- Include this file in any PHP page after login/session setup.
- Ensure the back-end implements the above REST routes and a WebSocket server at
ws://… - Adjust
config.apiUrlandconfig.wsUrlas needed. - Remove or comment out the initial
print_r($_SESSION); exit;in production.
Enjoy a seamless, real-time chat widget with file transfer and agent escalation!