<?php
$page_title = 'Messages';
require_once 'header.php';

$success = '';

// Mark as read
if (isset($_GET['read']) && $pdo) {
    $pdo->prepare("UPDATE contact_messages SET is_read=1 WHERE id=?")->execute([(int)$_GET['read']]);
    $success = 'Message marked as read.';
}

// Delete
if (isset($_GET['delete']) && $pdo) {
    $pdo->prepare("DELETE FROM contact_messages WHERE id=?")->execute([(int)$_GET['delete']]);
    $success = 'Message deleted.';
}

$messages = [];
if ($pdo) {
    $messages = $pdo->query("SELECT * FROM contact_messages ORDER BY created_at DESC")->fetchAll();
}
?>

<h1>Contact Messages</h1>
<p class="subtitle">View messages received from the contact form</p>

<?php if ($success): ?><div class="alert alert-success"><?php echo $success; ?></div><?php endif; ?>

<?php if (empty($messages)): ?>
<div class="card-admin">
  <p class="text-muted mb-0">No messages received yet.</p>
</div>
<?php else: ?>
<div class="card-admin">
  <div class="table-responsive">
    <table class="table table-admin mb-0">
      <thead>
        <tr>
          <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 foreach ($messages as $m): ?>
        <tr style="<?php echo !$m['is_read'] ? 'font-weight:600;' : ''; ?>">
          <td><?php echo htmlspecialchars($m['name']); ?></td>
          <td><a href="mailto:<?php echo htmlspecialchars($m['email']); ?>"><?php echo htmlspecialchars($m['email']); ?></a></td>
          <td><?php echo htmlspecialchars($m['subject'] ?: '—'); ?></td>
          <td style="max-width:300px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;"><?php echo htmlspecialchars($m['message']); ?></td>
          <td><?php echo date('j M Y, H:i', strtotime($m['created_at'])); ?></td>
          <td><?php echo $m['is_read'] ? '<span class="badge bg-success">Read</span>' : '<span class="badge bg-warning text-dark">New</span>'; ?></td>
          <td>
            <?php if (!$m['is_read']): ?>
            <a href="?read=<?php echo $m['id']; ?>" class="btn btn-sm btn-outline-success btn-admin">Mark Read</a>
            <?php endif; ?>
            <a href="?delete=<?php echo $m['id']; ?>" class="btn btn-sm btn-outline-danger btn-admin" onclick="return confirm('Delete this message?')">Delete</a>
          </td>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>
</div>
<?php endif; ?>

  </main>
</div>
<?php require_once __DIR__ . '/../includes/footer.php'; ?>
