<?php
require_once __DIR__ . '/config.php';
requireAdmin();
$pdo = getDB();
if (isset($_GET['read'])) {
    $pdo->prepare("UPDATE enquiries SET is_read = 1 WHERE id = ?")->execute([(int)$_GET['read']]);
    header('Location: enquiries.php');
    exit;
}
$enquiries = $pdo->query("SELECT * FROM enquiries ORDER BY created_at DESC")->fetchAll(PDO::FETCH_ASSOC);
$pageTitle = 'Enquiries';
require_once __DIR__ . '/includes/header.php';
?>
<div class="admin-page">
    <h1>Enquiries</h1>
    <table class="admin-table">
        <thead><tr><th>Date</th><th>Name</th><th>Email</th><th>Subject</th><th>Message</th><th>Read</th></tr></thead>
        <tbody>
            <?php foreach ($enquiries as $e): ?>
            <tr class="<?php echo !$e['is_read'] ? 'unread' : ''; ?>">
                <td><?php echo date('Y-m-d H:i', strtotime($e['created_at'])); ?></td>
                <td><?php echo htmlspecialchars($e['name']); ?></td>
                <td><?php echo htmlspecialchars($e['email']); ?></td>
                <td><?php echo htmlspecialchars($e['subject'] ?? '—'); ?></td>
                <td><?php echo htmlspecialchars(mb_substr($e['message'], 0, 80)); ?>...</td>
                <td>
                    <?php if (!$e['is_read']): ?>
                    <a href="enquiries.php?read=<?php echo $e['id']; ?>">Mark read</a>
                    <?php else: ?>✓<?php endif; ?>
                </td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
    <?php if (empty($enquiries)): ?>
    <p>No enquiries yet.</p>
    <?php endif; ?>
</div>
<?php require_once __DIR__ . '/includes/footer.php'; ?>
