<?php
// This block of PHP code, which handles the delete action and a subsequent redirect,
// must be executed before any HTML is sent to the browser.
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: contact_messages.php"); // Redirect to prevent re-deleting on refresh
    exit();
}

include 'admin_header.php';

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

    <div class="page-header">
        <h1>Bookings</h1>
    </div>

    <?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"><?php echo htmlspecialchars($row['email']); ?></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">
                            <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 message?');" 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(--text-secondary);">
            <i class="fas fa-calendar-check" style="font-size: 48px; margin-bottom: 15px; opacity: 0.3;"></i>
            <p>No new booking inquiries found.</p>
        </div>
    <?php endif; ?>

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