<?php
include('element/connection.php');



// Mark as read
if (isset($_GET['mark_read'])) {
    $id = (int)$_GET['mark_read'];
    mysqli_query($conn, "UPDATE contact_messages SET status='read' WHERE id=$id");
    header('Location: admin_messages.php');
}

// Delete message
if (isset($_GET['delete'])) {
    $id = (int)$_GET['delete'];
    mysqli_query($conn, "DELETE FROM contact_messages WHERE id=$id");
    header('Location: admin_messages.php');
}

// Fetch messages
$messages = mysqli_query($conn, "SELECT * FROM contact_messages ORDER BY created_at DESC");
?>

<!DOCTYPE html>
<html>
<head>
    <title>Admin - Contact Messages</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        .unread { background-color: #f0f7ff; font-weight: bold; }
        .badge-unread { background-color: #ff4444; color: white; padding: 5px 10px; border-radius: 20px; }
    </style>
</head>
<body>
    <div class="container mt-5">
        <h2>Contact Messages</h2>
        <table class="table table-bordered">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Name</th>
                    <th>Email</th>
                    <th>Subject</th>
                    <th>Message</th>
                    <th>Date</th>
                    <th>Status</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php while($msg = mysqli_fetch_assoc($messages)): ?>
                <tr class="<?php echo $msg['status'] == 'unread' ? 'unread' : ''; ?>">
                    <td><?php echo $msg['id']; ?></td>
                    <td><?php echo htmlspecialchars($msg['name']); ?></td>
                    <td><?php echo htmlspecialchars($msg['email']); ?></td>
                    <td><?php echo htmlspecialchars($msg['subject']); ?></td>
                    <td><?php echo htmlspecialchars(substr($msg['message'], 0, 50)) . '...'; ?></td>
                    <td><?php echo date('d-m-Y H:i', strtotime($msg['created_at'])); ?></td>
                    <td>
                        <?php if($msg['status'] == 'unread'): ?>
                            <span class="badge-unread">Unread</span>
                        <?php else: ?>
                            <span class="badge bg-success">Read</span>
                        <?php endif; ?>
                    </td>
                    <td>
                        <a href="?mark_read=<?php echo $msg['id']; ?>" class="btn btn-sm btn-primary">Mark Read</a>
                        <a href="?delete=<?php echo $msg['id']; ?>" class="btn btn-sm btn-danger" onclick="return confirm('Delete this message?')">Delete</a>
                    </td>
                </tr>
                <?php endwhile; ?>
            </tbody>
        </table>
    </div>
</body>
</html>