<?php 
require_once 'header.php'; 
$page_title = 'My Messages';

// Fetch all conversations for the logged-in user
$stmt = $conn->prepare("SELECT id, subject, status, last_reply_at FROM conversations WHERE user_id = ? ORDER BY last_reply_at DESC");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$conversations = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();
?>

<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
    <h1 class="h2"><i class="bi bi-chat-dots-fill me-2"></i>My Messages</h1>
    <a href="new-message.php" class="btn btn-primary"><i class="bi bi-plus-circle-fill me-1"></i> Start New Conversation</a>
</div>

<div class="card shadow-sm border-0">
    <div class="card-body">
        <div class="list-group list-group-flush">
            <?php if (empty($conversations)): ?>
                <div class="text-center p-5">
                    <i class="bi bi-chat-quote fs-1 text-muted"></i>
                    <h5 class="mt-3">You have no conversations.</h5>
                    <p class="text-muted">Start a new conversation to get in touch with our support team.</p>
                </div>
            <?php else: ?>
                <?php foreach ($conversations as $convo): ?>
                <a href="view-messages.php?id=<?php echo $convo['id']; ?>" class="list-group-item list-group-item-action">
                    <div class="d-flex w-100 justify-content-between">
                        <h6 class="mb-1 fw-bold"><?php echo htmlspecialchars($convo['subject']); ?></h6>
                        <small class="text-muted"><?php echo date('M d, Y', strtotime($convo['last_reply_at'])); ?></small>
                    </div>
                    <p class="mb-1">Status: <span class="badge bg-<?php echo ($convo['status'] == 'open') ? 'success' : 'secondary'; ?>"><?php echo ucfirst($convo['status']); ?></span></p>
                </a>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>
    </div>
</div>

<?php require_once 'footer.php'; ?>
