<?php
require_once 'admin-logic.php';

// --- Page-Specific Logic ---
$stmt = $conn->prepare("
    SELECT c.id, c.subject, c.status, c.last_reply_at, u.full_name 
    FROM conversations c
    JOIN users u ON c.user_id = u.id
    ORDER BY c.last_reply_at DESC
");
$stmt->execute();
$conversations = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();

$page_title = 'Support Conversations';
$current_page = 'manage-messages.php';
$active_category = 'bookingsMenu';

include 'admin-header.php';
?>

<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-quote-fill me-2"></i><?php echo $page_title; ?></h1>
</div>

<div class="card shadow-sm border-0">
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-hover align-middle">
                <thead class="table-light">
                    <tr>
                        <th>Subject</th>
                        <th>User</th>
                        <th>Last Update</th>
                        <th class="text-center">Status</th>
                        <th class="text-end">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($conversations)): ?>
                        <tr><td colspan="5" class="text-center p-5 text-muted">No conversations found.</td></tr>
                    <?php else: ?>
                        <?php foreach ($conversations as $convo): ?>
                        <tr>
                            <td class="fw-bold"><?php echo htmlspecialchars($convo['subject']); ?></td>
                            <td><?php echo htmlspecialchars($convo['full_name']); ?></td>
                            <td><?php echo date('M d, Y, g:i a', strtotime($convo['last_reply_at'])); ?></td>
                            <td class="text-center"><span class="badge bg-<?php echo ($convo['status'] == 'open') ? 'success' : 'secondary'; ?>"><?php echo ucfirst($convo['status']); ?></span></td>
                            <td class="text-end">
                                <a href="view-message.php?id=<?php echo $convo['id']; ?>" class="btn btn-sm btn-primary">View & Reply</a>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<?php include 'admin-footer.php'; ?>
