<?php
session_start();
include("config.php");

$res = mysqli_query($conn, "SELECT * FROM chat_messages ORDER BY timestamp ASC");
while($row = mysqli_fetch_assoc($res)) {
    $is_me = ($row['user_name'] == $_SESSION['user_name']);
    $side = $is_me ? 'align-self: flex-end; background: #27a760;' : 'align-self: flex-start; background: #2c3240;';
    $time = date("h:i A", strtotime($row['timestamp']));

    echo "<div style='max-width: 80%; padding: 10px; border-radius: 12px; margin: 5px; color: white; $side'>";
    echo "<small style='color: #adff2f; font-weight: bold;'>{$row['user_name']}</small><br>";
    if($row['message']) echo "<span>{$row['message']}</span><br>";
    
    if($row['file_path']) {
        if(strpos($row['file_type'], 'jpg') !== false || strpos($row['file_type'], 'png') !== false) {
            echo "<img src='{$row['file_path']}' style='width: 100%; border-radius: 8px; margin-top: 5px;'>";
        }
        echo "<br><a href='{$row['file_path']}' download style='color: white; font-size: 0.7rem;'>Download File <i class='fas fa-download'></i></a>";
    }
    echo "<div style='text-align: right; font-size: 0.65rem; opacity: 0.7;'>$time <i class='fas fa-check-double'></i></div>";
    echo "</div>";
}
?>