<?php
session_start();
include '../models/db_connection.php';

$logged_in_user_id = $_SESSION['user'];

$stmt = $pdo->prepare("SELECT * FROM messages WHERE receiver_id = ? OR sender_id = ? ORDER BY sendtime DESC");
$stmt->execute([$logged_in_user_id, $logged_in_user_id]);
$messages = $stmt->fetchAll();

foreach ($messages as $message) {
    echo "<p><strong>" . getUser($message['sender_id']) . ":</strong> " . $message['message'] . " <small>" . $message['sendtime'] . "</small></p>";
}

function getUser($user_id)
{
    global $pdo;
    $stmt = $pdo->prepare("SELECT username FROM users WHERE id = ?");
    $stmt->execute([$user_id]);
    return $stmt->fetchColumn();
}
