<?php 
include "../includes/db.php";
include "../includes/auth.php";
include "../includes/header.php"; 
include "../includes/sidebar.php"; 
?>

<h2 class="page-title">Messages</h2>

<table class="table table-bordered bg-white align-middle">
<tr>
    <th>#</th>
    <th>Name</th>
    <th>Email</th>
    <th>Subject</th>
    <th>Status</th>
    <th>Date</th>
    <th>Action</th>
</tr>

<?php
$result = $conn->query("SELECT * FROM messages ORDER BY created_at DESC");
if ($result && $result->num_rows > 0) {
    $i = 1;
    while($row = $result->fetch_assoc()):
?>
<tr class="<?= ($row['is_read'] ?? false) ? '' : 'fw-bold' ?>">
    <td><?= $i++ ?></td>
    <td><?= htmlspecialchars($row['name']) ?></td>
    <td><?= htmlspecialchars($row['email']) ?></td>
    <td><?= htmlspecialchars($row['subject']) ?></td>
    <td>
        <?= ($row['is_read'] ?? false) ? '<span class="badge bg-success">Read</span>' : '<span class="badge bg-warning">New</span>' ?>
    </td>
    <td><?= date('M d, Y H:i', strtotime($row['created_at'])) ?></td>
    <td>
        <a href="message_view.php?id=<?= $row['id'] ?>" class="btn btn-sm btn-primary">View</a>
        <button onclick="deleteMessage(<?= $row['id'] ?>)" class="btn btn-sm btn-danger">Delete</button>
    </td>
</tr>
<?php endwhile;
} else {
    echo '<tr><td colspan="7" class="text-center text-muted">No messages found</td></tr>';
}
?>
</table>

<script>
function deleteMessage(id) {
    if (confirm('Are you sure you want to delete this message?')) {
        fetch('messages_delete.php', {
            method: 'POST',
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            body: 'id=' + id
        }).then(() => location.reload());
    }
}
</script>

<?php include "../includes/footer.php"; ?>
