<?php
// Database connection
$con = mysqli_connect("localhost", "chemtech", "chemtech@123", "chemtech");
if (!$con) {
    die("Connection failed: " . mysqli_connect_error());
}

// Fetch all messages from the chat_messages table ordered by timestamp
$query = "SELECT * FROM chat_messages ORDER BY timestamp ASC";
$result = mysqli_query($con, $query);

// Check if there are messages
if (mysqli_num_rows($result) > 0) {
    // Loop through and display messages
    while ($row = mysqli_fetch_assoc($result)) {
        echo "<div id='message-" . $row['id'] . "'>";
        echo "<strong>" . ucfirst($row['sender']) . ":</strong> " . htmlspecialchars($row['message']);
        echo " <small>[" . $row['timestamp'] . "]</small>";
        
        // Show a reply button if the message is from a user (i.e., sender = 'user')
        if ($row['sender'] == 'user') {
            echo " <button onclick='replyToMessage(" . $row['id'] . ")'>Reply</button>";
        }
        echo "</div><hr>";
    }
} else {
    echo "No messages yet.";
}

// Close database connection
mysqli_close($con);
?>
