<?php
include 'admin-header.php';

$message = '';
// --- ACTION HANDLING ---
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['message_id'])) {
    $message_id = intval($_POST['message_id']);

    if (isset($_POST['mark_read'])) {
        $stmt = $conn->prepare("UPDATE contact_messages SET is_read = 1 WHERE id = ?");
        $stmt->bind_param("i", $message_id);
        $stmt->execute();
        $message = '<div class="alert alert-info">Message marked as read.</div>';
    } elseif (isset($_POST['delete_message'])) {
        $stmt = $conn->prepare("DELETE FROM contact_messages WHERE id = ?");
        $stmt->bind_param("i", $message_id);
        $stmt->execute();
        $message = '<div class="alert alert-success">Message deleted successfully.</div>';
    }
}

// --- DATA FETCHING ---
$view = $_GET['view'] ?? 'unread';
$where_clause = ($view == 'unread') ? "WHERE is_read = 0" : "";
$sql = "SELECT * FROM contact_messages $where_clause ORDER BY created_at DESC";
$messages_result = $conn->query($sql);

$unread_count = $conn->query("SELECT COUNT(*) as total FROM contact_messages WHERE is_read = 0")->fetch_assoc()['total'];
?>

<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">Contact Form Messages</h1>
</div>
<?php echo $message; ?>

<ul class="nav nav-tabs mb-3">
    <li class="nav-item">
        <a class="nav-link <?php if($view == 'unread') echo 'active'; ?>" href="?view=unread">
            Unread <span class="badge bg-danger"><?php echo $unread_count; ?></span>
        </a>
    </li>
    <li class="nav-item">
        <a class="nav-link <?php if($view == 'all') echo 'active'; ?>" href="?view=all">All Messages</a>
    </li>
</ul>

<div class="card shadow-sm">
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-hover align-middle">
                <thead class="table-dark">
                    <tr>
                        <th>From</th>
                        <th>Subject</th>
                        <th>Message</th>
                        <th>Received</th>
                        <th class="text-center">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if ($messages_result && $messages_result->num_rows > 0): ?>
                        <?php while($msg = $messages_result->fetch_assoc()): ?>
                        <tr class="<?php echo $msg['is_read'] == 0 ? 'fw-bold' : ''; ?>">
                            <td>
                                <?php echo htmlspecialchars($msg['name']); ?><br>
                                <small class="text-muted"><?php echo htmlspecialchars($msg['email']); ?></small>
                            </td>
                            <td><?php echo htmlspecialchars($msg['subject']); ?></td>
                            <td><?php echo substr(htmlspecialchars($msg['message']), 0, 100); ?>...</td>
                            <td><?php echo date('M d, Y H:i A', strtotime($msg['created_at'])); ?></td>
                            <td class="text-center">
                                <div class="btn-group">
                                <?php if ($msg['is_read'] == 0): ?>
                                    <form method="POST" class="d-inline">
                                        <input type="hidden" name="message_id" value="<?php echo $msg['id']; ?>">
                                        <button type="submit" name="mark_read" class="btn btn-sm btn-outline-success">Mark Read</button>
                                    </form>
                                <?php endif; ?>
                                <form method="POST" class="d-inline" onsubmit="return confirm('Are you sure you want to delete this message?');">
                                    <input type="hidden" name="message_id" value="<?php echo $msg['id']; ?>">
                                    <button type="submit" name="delete_message" class="btn btn-sm btn-outline-danger">Delete</button>
                                </form>
                                </div>
                            </td>
                        </tr>
                        <?php endwhile; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="5" class="text-center text-muted p-4">
                                <?php echo $view == 'unread' ? 'No unread messages. Great job!' : 'No messages found.'; ?>
                            </td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

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