<?php
session_start();
include('../../../includes/config.php');

$message_id = intval($_GET['id']);
$user_id = $_SESSION['user_id'];

$query = "SELECT m.*, 
          CONCAT(s.first_name, ' ', s.last_name) AS sender_name, 
          CONCAT(r.first_name, ' ', r.last_name) AS receiver_name 
          FROM messages m
          JOIN users s ON m.sender_id = s.id
          JOIN users r ON m.receiver_id = r.id
          WHERE m.id = ? AND (m.sender_id = ? OR m.receiver_id = ?)";

$stmt = $conn->prepare($query);
$stmt->bind_param("iii", $message_id, $user_id, $user_id);
$stmt->execute();
$result = $stmt->get_result()->fetch_assoc();

if (!$result) {
    echo "Message not found.";
    exit;
}

// Mark as read
if ($result['receiver_id'] == $user_id && $result['status'] == 'unread') {
    $conn->query("UPDATE messages SET status='read' WHERE id = $message_id");
}
?>

<h2>Message Detail</h2>
<p><strong>From:</strong> <?= htmlspecialchars($result['sender_name']) ?></p>
<p><strong>To:</strong> <?= htmlspecialchars($result['receiver_name']) ?></p>
<p><strong>Subject:</strong> <?= htmlspecialchars($result['subject']) ?></p>
<p><strong>Message:</strong><br><?= nl2br(htmlspecialchars($result['message'])) ?></p>
<p><small>Sent on <?= $result['sent_at'] ?></small></p>
