connect_error) { die("Connection failed: " . $conn->connect_error); } // Handle sending messages via WebSocket if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['message'])) { $message = htmlspecialchars($_POST['message']); $stmt = $conn->prepare("INSERT INTO messages (sender_id, group_id, message, timestamp) VALUES (?, ?, ?, NOW())"); $stmt->bind_param("iis", $sender_id, $group_id, $message); $stmt->execute(); $stmt->close(); // Return message with username and timestamp for WebSocket $response = [ 'username' => $_SESSION['username'], 'message' => $message, 'timestamp' => date('Y-m-d H:i:s'), 'sender_id' => $sender_id ]; echo json_encode($response); exit; } // Fetch messages for the group $stmt = $conn->prepare("SELECT users.username, messages.message, messages.timestamp FROM messages JOIN users ON messages.sender_id = users.id WHERE group_id = ? ORDER BY messages.timestamp ASC"); $stmt->bind_param("i", $group_id); $stmt->execute(); $result = $stmt->get_result(); $messages = $result->fetch_all(MYSQLI_ASSOC); $stmt->close(); // Update user status to "online" in the database $update_status = $conn->prepare("UPDATE users SET status = 'online' WHERE id = ?"); $update_status->bind_param("i", $sender_id); $update_status->execute(); $update_status->close(); // Fetch all users for online status display $users = $conn->query("SELECT username, status FROM users"); ?>