setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Fetch all users for the contact list $stmt = $pdo->prepare("SELECT id, username FROM users WHERE id != ? ORDER BY username ASC"); $stmt->execute([$current_user_id]); $users = $stmt->fetchAll(); // Fetch all rooms the user is a member of $stmt = $pdo->prepare( "SELECT r.id, r.name, r.is_private, (SELECT u.username FROM users u JOIN room_members rm_other ON u.id = rm_other.user_id WHERE rm_other.room_id = r.id AND rm_other.user_id != ?) AS private_chat_partner FROM rooms r JOIN room_members rm ON r.id = rm.room_id WHERE rm.user_id = ? ORDER BY r.is_private, r.name ASC" ); $stmt->execute([$current_user_id, $current_user_id]); $rooms = $stmt->fetchAll(); // If user has no rooms, create a "General" one and add them to it if (empty($rooms)) { $stmt = $pdo->prepare("INSERT INTO rooms (name, created_by) VALUES ('General', ?)"); $stmt->execute([$current_user_id]); $general_room_id = $pdo->lastInsertId(); $stmt = $pdo->prepare("INSERT INTO room_members (room_id, user_id) VALUES (?, ?)"); $stmt->execute([$general_room_id, $current_user_id]); // Re-fetch rooms $stmt->execute([$current_user_id, $current_user_id]); $rooms = $stmt->fetchAll(); } // Determine the current room $current_room_id = $_GET['room_id'] ?? $rooms[0]['id'] ?? null; $current_room = null; if ($current_room_id) { foreach ($rooms as $room) { if ($room['id'] == $current_room_id) { $current_room = $room; break; } } } // If the user is not a member of the requested room, redirect to their first room if ($current_room_id && !$current_room) { header("Location: index.php"); exit; } // Messages are now fetched by the frontend $messages = []; $last_message_id = 0; ?> AD Messaging App

Messages

Theme

Loading messages...

Create or select a room to start chatting.