<?php
session_start();
include_once("../config/db.php");

// Security: Ensure user is an admin before performing any action.
if(!isset($_SESSION['admin'])){
    header("Location: login.php");
    exit();
}

if(isset($_GET['delete'])){
    $id = $_GET['delete'];
    $stmt = mysqli_prepare($conn, "DELETE FROM contact_messages WHERE id=?");
    mysqli_stmt_bind_param($stmt, "i", $id);
    mysqli_stmt_execute($stmt);
    header("Location: booking.php"); // Redirect to prevent re-deleting on refresh
    exit();
}

include 'admin_header.php';

$result = mysqli_query($conn, "SELECT * FROM contact_messages WHERE email NOT LIKE 'Interested in:%' OR email IS NULL ORDER BY id DESC");
?>

<div class="page-header">
    <h1>Contact Messages</h1>
</div>

<div class="content-wrapper">
    <?php if (mysqli_num_rows($result) > 0): ?>
        <div class="message-list">
            <?php while ($row = mysqli_fetch_assoc($result)): ?>
                <div class="message-card">
                    <div class="message-header">
                        <div>
                            <div class="message-sender"><?php echo htmlspecialchars($row['name']); ?></div>
                            <div class="message-subject">
                                Arrival: <?php echo htmlspecialchars(date("M d, Y", strtotime($row['arrival_date']))); ?> | Guests: <?php echo htmlspecialchars($row['num_people']); ?>
                            </div>
                        </div>
                        <div class="message-date"><?php echo date("M d, Y, g:i A", strtotime($row['created_at'])); ?></div>
                    </div>
                    <div class="message-footer">
                        <div class="message-contact">
                            <?php if(!empty($row['email'])): ?><a href="mailto:<?php echo htmlspecialchars($row['email']); ?>"><i class="fas fa-envelope"></i> <?php echo htmlspecialchars($row['email']); ?></a><?php endif; ?>
                            <span><i class="fas fa-phone"></i> <?php echo htmlspecialchars($row['mobile']); ?></span>
                        </div>
                        <div class="message-actions">
                            <a href="?delete=<?php echo $row['id']; ?>" class="delete" onclick="return confirm('Are you sure you want to delete this booking?');" title="Delete">
                                <i class="fas fa-trash"></i> Delete
                            </a>
                        </div>
                    </div>
                </div>
            <?php endwhile; ?>
        </div>
    <?php else: ?>
        <div class="message-card" style="padding: 40px; text-align: center; color: var(--content-text-secondary);">
            <i class="fas fa-envelope-open-text" style="font-size: 48px; margin-bottom: 15px; opacity: 0.3;"></i>
            <p>No contact messages found.</p>
        </div>
    <?php endif; ?>
</div>

<?php include 'admin_footer.php'; ?>